title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
tag
stringclasses
707 values
level
stringclasses
3 values
question_hints
stringlengths
19
3.98k
view_count
int64
8
630k
vote_count
int64
5
10.4k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
Minimum Time to Complete Trips
minimum-time-to-complete-trips
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 do not influence the trips of any other bus. You are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips.
Array,Binary Search
Medium
For a given amount of time, how can we count the total number of trips completed by all buses within that time? Consider using binary search.
756
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long minimumTime(vector<int>& time, int totalTrips) {\n #define ll long long\n ll start = 1;\n ll end = 1e14;\n while(start <= end){\n ll trip = 0;\n ll mid = start + (end - start)/2;\n for(int i=0;i<time.size();i++)\n trip += mid / time[i];\n if(trip < totalTrips){\n start = mid + 1;\n }\n else \n end = mid - 1;\n }\n return start;\n }\n};\n```
107,711
Minimum Time to Complete Trips
minimum-time-to-complete-trips
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 do not influence the trips of any other bus. You are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips.
Array,Binary Search
Medium
For a given amount of time, how can we count the total number of trips completed by all buses within that time? Consider using binary search.
304
5
# Intuition\nThe brute force approach would be to start from time t=1 and increase it to check whether we can achieve the required number of trips in time t. This approach would cause TLE because of the constraints given.\n\n\n# Approach\nNow from the brute force approach we can work towards a better solution. In the brute force approach we are using all values of time between t=1 to the maximum time needed. The maximum time needed would be totalTrips*(maximum time taken by a bus to complete one trip).\n\nNow, instead of exploring all the values in the range, we can use binary search to find the minimum value.\n1. The minimum time would be 1 second. So, **low=1**. The maximum time would be **high=totalTrips * (maximum value in time array)** .\n2. Until low<high we will do the following:\n - Find the mid value: **mid=(low+high)/2**.\n - Now, we would check whether it is enough to complete the totalTrips in mid time. Each bus would do **mid/time[i]** trips. We can iterate the array time to calculate the total trips. \n - If the mid value is more than enough to take totalTrips number of trips. Then our range would become low to mid (we are including mid as it can be the lowest value too).\n But if it\'s not enough the range would be mid+1 to high.\n \n\n# Code\n### 1. Brute force \n```\nlong long minimumTime(vector<int>& time, int totalTrips) {\n long long trips=0; // trips would store the trips completed until t time\n int t=1; \n while(trips<totalTrips){ // if trips==totalTrips, we can break out of the loop \n for(int i=0;i<time.size();++i){ \n if(t%time[i]==0) trips++; // if t is divisble by time[i] that means bus i has completed one more trip in time t.\n }\n t++;\n }\n return t-1;\n}\n \n```\n### 2. Binary Search\n```\nlong long minimumTime(vector<int>& time, int totalTrips) {\n long long maxtime=*max_element(time.begin(),time.end()); // maximum time taken by a bus to complete one trip\n long long l=1, r=totalTrips*maxtime; // time range in which minimum time lies\n while(l<r){\n long long mid=(l+r)/2, actualTrips=0; // actualTrips would store the trips completed in time 0 to mid.\n for(int i=0;i<time.size();i++){\n actualTrips+=mid/time[i]; \n }\n if(actualTrips<totalTrips) l=mid+1; // if the time mid is not enough, then the range would become mid+1 to r.\n else r=mid; // if the time mid is enough than the minimum lies in the range l to mid.\n }\n return l;\n}\n\n```
107,724
Minimum Time to Complete Trips
minimum-time-to-complete-trips
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 do not influence the trips of any other bus. You are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips.
Array,Binary Search
Medium
For a given amount of time, how can we count the total number of trips completed by all buses within that time? Consider using binary search.
12,639
109
**This is what we call Binary Search on Answers. First we need to see that what can be the range of time. The range of time will be lowest value of the time array and highest value will be minimum value in the time array multiplied by totalTrips because at worst case the bus with min time will do all trips which will be minimum time taken to do all trips or you can take maximum value in time array multiplied by totalTrips if you are thinking in this way that at worstcase the bus with highest time will do all the trips. As the question is asking for minimum time so first one makes more sense than later one. But both are correct because obviously it will be eliminating right half if it gets totalTrips done with that particular time. Then we just traverse through the ranges and using Binary Search we check if the totalTrips is possible to do in that time or not. If possible then it\'s a possible answer and we are not sure that it\'s our minimum time so we do high=mid and if it\'s not possible then we move low to mid+1 because obviously we can\'t perform our task within that time. Atlast we just return the low that points to the minimum time that will take to complete the totalTrips.**\n```\nclass Solution {\n public long minimumTime(int[] time, int totalTrips) {\n long low=Long.MAX_VALUE;\n long high=0;\n long min=Long.MAX_VALUE;\n for(int it:time){\n low=Math.min(low,it);\n min=Math.min(min,it);\n }\n high=totalTrips*min;\n while(low<high){\n long mid=low+(high-low)/2;\n if(blackbox(mid,totalTrips,time)){\n high=mid;\n }\n else\n low=mid+1;\n }\n return low;\n }\n public boolean blackbox(long isvalidtime,int totalTrips,int[] time){\n long trips=0;\n for(int it:time){\n trips+=isvalidtime/it;\n }\n if(trips>=totalTrips)\n return true;\n return false;\n }\n}\n```\n![image]()\n
107,725
Minimum Time to Complete Trips
minimum-time-to-complete-trips
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 do not influence the trips of any other bus. You are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips.
Array,Binary Search
Medium
For a given amount of time, how can we count the total number of trips completed by all buses within that time? Consider using binary search.
23,525
308
**Good Binary Search Problems**\n* [1552. Magnetic Force Between Two Balls]()\n* [1870. Minimum Speed to Arrive on Time]()\n* [875. Koko Eating Bananas]()\n* [1011. Capacity To Ship Packages Within D Days]()\n* [1283. Find the Smallest Divisor Given a Threshold]()\n* [1482. Minimum Number of Days to Make m Bouquets]()\n* [2064. Minimized Maximum of Products Distributed to Any Store]()\n* [1231. Divide Chocolate]()\n* [774. Minimize Max Distance to Gas Station]()\n* [410. Split Array Largest Sum]()\n* [1539. Kth Missing Positive Number]()\n* [162. Find Peak Element]()\n* [441. Arranging Coins]()\n* [378. Kth Smallest Element in a Sorted Matrix]()\n* [287. Find the Duplicate Number]()\n* [209. Minimum Size Subarray Sum]()\n* [1760. Minimum Limit of Balls in a Bag]()\n* [1631. Path With Minimum Effort]()\n* [2070. Most Beautiful Item for Each Query]()\n* [475. Heaters]()\n* [1818. Minimum Absolute Sum Difference]()\n* [1838. Frequency of the Most Frequent Element]()\n* [778. Swim in Rising Water]()\n* [668. Kth Smallest Number in Multiplication Table]()\n* [878. Nth Magical Number]()\n* [719. Find K-th Smallest Pair Distance]()\n* [2141. Maximum Running Time of N Computers]()\n* [1287. Element Appearing More Than 25% In Sorted Array]()\n* [34. Find First and Last Position of Element in Sorted Array]()\n* [774. Minimize Max Distance to Gas Station]()\n* [1150. Check If a Number Is Majority Element in a Sorted Array]()\n* [1482. Minimum Number of Days to Make m Bouquets]()\n* [981. Time Based Key-Value Store]()\n* [1201. Ugly Number III]()\n* [704. Binary Search]()\n* [69. Sqrt(x)]()\n* [35. Search Insert Position]()\n* [278. First Bad Version]()\n* \n* \n* For more problems you can refer to this page :- \n\n![image]()\n
107,726
Minimum Time to Complete Trips
minimum-time-to-complete-trips
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 do not influence the trips of any other bus. You are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips.
Array,Binary Search
Medium
For a given amount of time, how can we count the total number of trips completed by all buses within that time? Consider using binary search.
3,042
12
\n# Approach\n1. minimum time can be 1, less than 1 can not possible.\n2. maximum time can be (minimum element of given time array * total trips).\n3. we use binary search to chose optimally minimum time that can be required to complete total trips\n4. when number of trips completed by \'mid\' time >= total trips, then our ans can be \'mid\' time, but less than \'mid\' time can be possible, so we reduce our search space.\n5. when number of trips completed by \'mid\' time < total trips, then our ans can not be \'mid\' time, but greater than \'mid\' time can be possible, so we increase our start to increase mid.\n# Complexity\n- Time complexity:$$O(N*logN)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long func(vector<int>&time, long long k)\n {\n long long ans=0;\n for(int i=0;i<time.size();i++)\n {\n ans+= k/time[i];\n }\n return ans;\n }\n long long minimumTime(vector<int>& time, int totalTrips) \n {\n long long s=1,e,ans=LONG_MAX;\n e = 1LL*(*min_element(time.begin(),time.end())) * totalTrips;\n while(s<=e)\n {\n long long mid = s + (e-s)/2;\n long long x = func(time,mid);\n if(x>=totalTrips)\n {\n ans = min(ans,mid);\n e = mid-1;\n }\n else\n {\n s = mid+1;\n }\n }\n return ans;\n }\n};\n```\n**If you feel this helpful then plz like and upvote this solution \uD83D\uDE0A\nKEEP LEETCODING.............**\n![upvote.png]()\n
107,727
Minimum Time to Finish the Race
minimum-time-to-finish-the-race
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. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race.
Array,Dynamic Programming
Hard
What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values?
8,532
166
This problem seems very hard at first glance, but would be way easier with just one observation.\n\n# Observation\n- Given `changeTime <= 10^5`, it won\'t be optimal if we use any tire consecutively without change for larger than `18` laps.\n- Let\'s consider the extreme case, when `f_i == 1` and `r_i == 2`\n\n| consecutive laps | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10\n|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|\n| time on the last lap | 1 | 2 | 4 | 8 | 16| 32| 64|128|256| 512\n\n| consecutive laps | 11 | 12 | 13|14|15|16|17|18|\n|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|\n| time on the last lap |1024|2048|4096|8192|16384|32768|65536|**131072**|\n\n- it is obvious that at the `18-th` consecutive lap, it is alway better to change a tire (even when `f_i` and `r_i` are given their smallest possible values).\n- this observation leads to two lemmas\n##### Lemma 1.\n- If `numLaps >= 18`, we must change tire in some point of time in any optimal way.\n##### Lemma 2.\n- After changing a tire, an optimal way won\'t have the tire running for more than `18` consecutive laps.\n\n### Algorithm\n- from the above discussion, we can form a dp like:\n\t- `dp[x] :=` the minimum time to finish `x` laps\n\t- base case: `dp[1]` = `min(f_i)` among all tires\n\t- transition: `dp[x] = min(dp[j] + changeTime + dp[x-j])` among all *possible `j`s*\n\t\t- meaning: the minimum time to finish `x` laps is the minimum time to finish `j` laps first **and change a tire at the end of `j`-th lap**, plus the minimum time to finish the last `x-j` laps.\n\t\t- which `j`s are *possible* ?\n\t\t\t- from **Lemma 2.** we know `j >= x-18` must hold.\n\t\t\t- It leads to a constant time transition.\n\t- note that if `x < 18`, it\'s possible that an optimal solution never changes a tire.\n- code\n```\nclass Solution {\npublic:\n int minimumFinishTime(vector<vector<int>>& tires, int changeTime, int numLaps) {\n int n = tires.size();\n // to handle the cases where numLaps is small\n\t\t// without_change[i][j]: the total time to run j laps consecutively with tire i\n vector<vector<int>> without_change(n, vector<int>(20, 2e9));\n for (int i = 0; i < n; i++) {\n without_change[i][1] = tires[i][0];\n for (int j = 2; j < 20; j++) {\n if ((long long)without_change[i][j-1] * tires[i][1] >= 2e9)\n break;\n without_change[i][j] = without_change[i][j-1] * tires[i][1];\n }\n // since we define it as the total time, rather than just the time for the j-th lap\n\t\t\t// we have to make it prefix sum\n for (int j = 2; j < 20; j++) {\n if ((long long)without_change[i][j-1] + without_change[i][j] >= 2e9)\n break;\n without_change[i][j] += without_change[i][j-1];\n }\n }\n \n\t\t// dp[x]: the minimum time to finish x laps\n vector<int> dp(numLaps+1, 2e9);\n for (int i = 0; i < n; i++) {\n dp[1] = min(dp[1], tires[i][0]);\n }\n for (int x = 1; x <= numLaps; x++) {\n if (x < 20) {\n\t\t\t\t// x is small enough, so an optimal solution might never changes tires!\n for (int i = 0; i < n; i++) {\n dp[x] = min(dp[x], without_change[i][x]);\n }\n }\n for (int j = x-1; j > 0 && j >= x-18; j--) {\n dp[x] = min(dp[x], dp[j] + changeTime + dp[x-j]);\n }\n }\n \n return dp[numLaps];\n }\n};\n```\n- Time Complexity: (let `n := tires.size()`)\n\t- preprocess `without_change`: **O(n)**\n\t- `dp`: **O(18 * numLaps + 20 * n)** -> **O(numLaps + n)**\n- Space Complexity:\n\t- `without_change`: **O(n)**\n\t- `dp`: **O(numLaps)**\n\n### Another Observation\n- if `f_i <= f_j` and `r_i <= r_j`, it is always "not worse" to pick tire `i` over tire `j`. So we can do some preprocess to remove all such tires.\n- won\'t be better in time complexity (since we now have to sort `tires`), but might improve the runtime (and space allocated)\n- code\n```\nclass Solution {\nprivate:\n vector<vector<int>> preprocess(vector<vector<int>>& tires) {\n sort(tires.begin(), tires.end());\n vector<vector<int>> new_tires;\n for (auto& t : tires) {\n if (new_tires.empty() || new_tires.back()[1] > t[1]) {\n new_tires.push_back(t);\n }\n }\n return new_tires;\n }\npublic:\n int minimumFinishTime(vector<vector<int>>& tires, int changeTime, int numLaps) {\n // remove those will never be used\n tires = preprocess(tires);\n int n = tires.size();\n\t\t\n\t\t// ... (rest are the same)\n\t\t\n\t\treturn dp[numLaps];\n\t}\n}\n```\n# Similar Problems\n- it reminds me of the following problems\n\t- [LC 1105 - Filling Bookcase Shelves]() (challenge: solve this in **O(n lg n)** time.)\n\t- [LC 1687 - Delivering Boxes from Storage to Ports]()
107,760
Minimum Time to Finish the Race
minimum-time-to-finish-the-race
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. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race.
Array,Dynamic Programming
Hard
What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values?
6,724
111
**Intuition:** We have a lot of tires, but the number of laps is limited to 1,000.\n \nWe first compute how long it takes to finish `n` laps with each tire without changing it.\n \n> Optimization: it only makes sense to use a tire while the lap time is less than `fi + changeTime`.\n \nWe track the best time to complete `i` laps, across all tires, in the `best` array.\n \nAfter that, we run DFS, memoising it by the number of laps to race (`dp`): \n- For remaining `laps`, we find the best time by trying to race `i` laps, change a tire, and recurse on `laps - i` remaining laps.\n- For `i` laps, we pick the `best` time to finish those laps. \n\n#### Approach 1: Top-Down DP\n**C++**\n```cpp\nint dp[1001] = {}, best[1001] = {}, max_laps = 0;\nint dfs(int laps, int changeTime) {\n if (laps == 0)\n return -changeTime;\n if (!dp[laps]) {\n dp[laps] = INT_MAX;\n for (int i = 1; i <= min(laps, max_laps); ++i)\n dp[laps] = min(dp[laps], best[i] + changeTime + dfs(laps - i, changeTime));\n }\n return dp[laps];\n}\nint minimumFinishTime(vector<vector<int>>& tires, int changeTime, int numLaps) {\n for (auto &t : tires) {\n long long lap_time = t[0], time = t[0];\n for (int lap = 1; lap <= numLaps && lap_time < t[0] + changeTime; ++lap) {\n max_laps = max(max_laps, lap);\n if (best[lap] == 0 || best[lap] > time)\n best[lap] = time;\n lap_time *= t[1];\n time += lap_time;\n }\n }\n return dfs(numLaps, changeTime);\n}\n```\n#### Approach 2: Bottom-Up DP\nIf we notice that `ri >= 2`, we can realize that we cannot use a tire for more than 18 laps. Otherwise, the lap time will exceed the change time (100000).\n\nThis fact allows us to save on memory for both storing the `best` lap times, and for the tabulation (as we only need to go up to 19 steps back).\n\n**C++**\nA bit compressed - just for fun.\n```cpp\nint minimumFinishTime(vector<vector<int>>& tires, int changeTime, int numLaps) {\n int constexpr sz = 19;\n long long best[sz] = {[0 ... sz - 1] = INT_MAX}, dp[sz] = {};\n for (auto &t : tires)\n for (long long i = 1, lap = t[0], tot = 0; lap < t[0] + changeTime; ++i) {\n tot += lap;\n best[i] = min(best[i], tot);\n lap *= t[1];\n }\n for (int i = 1; i <= numLaps; ++i) {\n dp[i % sz] = INT_MAX;\n for (int j = 1; j <= min(i, sz - 1); ++j)\n dp[i % sz] = min(dp[i % sz], best[j] + dp[(i - j) % sz] + changeTime);\n }\n return dp[numLaps % sz] - changeTime;\n}\n```
107,761
Minimum Time to Finish the Race
minimum-time-to-finish-the-race
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. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race.
Array,Dynamic Programming
Hard
What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values?
2,167
28
See my latest update in repo [LeetCode]()\n\n## Solution 1. DP\n\nThe `best[i]` is the least time we need to finish `i+1` laps **using a single tire**. For each tire, we try to use it to update the `best` values.\n\nThe `dp` part is doing knapsack using the `best` values to get total `numLaps` laps.\n\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(N * numLaps)\n// Space: O(numLaps)\nclass Solution {\npublic:\n int minimumFinishTime(vector<vector<int>>& A, int change, int numLaps) {\n int N = A.size(), len = 0;\n vector<long> best(numLaps, LONG_MAX), dp(numLaps + 1, INT_MAX);\n for (int i = 0; i < N; ++i) {\n long f = A[i][0], r = A[i][1], sum = change, p = 1; // We assume we also need `change` time to use the first tire so that we don\'t need to treat the first tire as a special case\n for (int j = 0; j < numLaps; ++j) {\n sum += f * p;\n if (f * p >= f + change) break; // If using the same tire takes no less time than changing the tire, stop further using the current tire\n best[j] = min(best[j], sum);\n len = max(len, j + 1);\n p *= r;\n }\n }\n dp[0] = 0; // dp[i + 1] is the minimum time to finish `numLaps` laps\n for (int i = 0; i < numLaps; ++i) {\n for (int j = 0; j < len && i - j >= 0; ++j) { // try using the same tire in the last `j+1` laps\n dp[i + 1] = min(dp[i + 1], dp[i - j] + best[j]);\n }\n }\n return dp[numLaps] - change; // minus the `change` we added to the first tire\n }\n};\n```
107,762
Minimum Time to Finish the Race
minimum-time-to-finish-the-race
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. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race.
Array,Dynamic Programming
Hard
What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values?
1,755
20
Intuition - since the minimum value of r is 2, this means that we can optimally use a tire for atmost 16 laps (2^15 will be greater than the max changeTime after that)\n\nWe can calculate the min cost for first 16 laps if we use only one tire and then use this info to calculate the minimum time taken for each lap considering the switches.\n\n```\nclass Solution:\n def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int:\n \n optimal = [math.inf]*(numLaps+1)\n for a,b in tires:\n curCost = a\n curTire = 1\n totalCost = a\n while curTire<=16 and curTire<(numLaps+1):\n optimal[curTire] = min(optimal[curTire], totalCost)\n curCost = curCost * b\n totalCost = curCost+totalCost\n curTire+=1\n\n for i in range(1,numLaps+1):\n for j in range(i-1):\n #if we switch tire at jth point \n optimal[i] = min(optimal[i],changeTime + optimal[j+1] + optimal[i-(j+1)])\n \n\n return optimal[-1]\n\t\t```
107,763
Minimum Time to Finish the Race
minimum-time-to-finish-the-race
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. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race.
Array,Dynamic Programming
Hard
What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values?
2,759
44
## When we will change tyre?\n\nWe will change tyre when current Time for a Lap is >= f + change time.\n\nBecause by changing tyre we are using the same or less time than the time required for a consecutive lap without change, and also it will benefit the future laps too.\n\nEx: f = 2, r = 3, changeTime = 10\nLap1 : Cost = 2, Total = 2\nLap2 : Cost = Cost of Last Lap * r = 6, Total = 8\nLap3 : Cost 6*3 = 18 , Now 18>change TIme+f\nHence we will change tyre\n\n## Approach:\n\ndp[i] denotes the min time to travel i laps.\n\nWe first fill the dp without changing tyres and then modify and fill the remaining states of dp by recurrence relation:\n\n<b>dp[i] = min(dp[i] ,changeTime + dp[j] + dp[i-j])\n\nBasically we are breaking i laps into parts j and (i-j) laps (i>=j).\nAnd we have already calculated dp[j] and dp[i-j].\n\n## Code:\n```\ntypedef long long ll;\n\nclass Solution {\npublic:\n\n void fillDPWithoutChange(vector<ll>& dp, int changeTime, vector<vector<int>>& tires)\n {\n for (vector<int>& currTyre : tires)\n {\n ll f = currTyre[0];\n ll r = currTyre[1];\n dp[1] = min(dp[1], f);\n ll lastLapTime = f;\n ll totalTime = f;\n ll lapCount = 2;\n while (lastLapTime * r < f + changeTime && lapCount < dp.size())\n\t\t\t//we can prove that this loop will not run many times because we are\n\t\t\t//moving in powers of r and even a small r like 2 will terminate this\n\t\t\t//loop under 20 iterations.\n {\n ll currLapTime = lastLapTime * r;\n totalTime += currLapTime;\n dp[lapCount] = min(dp[lapCount], totalTime);\n lastLapTime = currLapTime;\n lapCount++;\n }\n }\n }\n\n void modifyDPforChange(vector<ll>& dp, int changeTime, vector<vector<int>>& tires)\n {\n for (ll i = 1; i < dp.size(); ++i)\n {\n for (ll j = 1; j <= i; ++j)\n {\n dp[i] = min(dp[i], changeTime + dp[j] + dp[i - j]);\n }\n }\n }\n\n int minimumFinishTime(vector<vector<int>>& tires, int changeTime, int numLaps) {\n vector<ll> dp(numLaps + 1, LLONG_MAX);\n dp[0] = 0;\n fillDPWithoutChange(dp, changeTime, tires);\n modifyDPforChange(dp, changeTime, tires);\n return dp[numLaps];\n }\n};\n```\n\nTime Complexity : O(max(numLaps^2,number of tyres))\nSpace: O(numLaps)\n\nYou can ask your doubts in comment section.\nUpvote if you found this helpful.
107,764
Minimum Time to Finish the Race
minimum-time-to-finish-the-race
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. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race.
Array,Dynamic Programming
Hard
What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values?
1,237
12
\n\n- `dp[i]` represents for the minimum time to complete `i + 1` laps.\n- `minimum[i]` represents for the minimum time to complete `i + 1` laps without changing a tire.\n- `dp[i] = min(dp[i - j - 1] + changeTime + minimum[j] for j in range(len(minimum)))`\n- don\u2019t forget about the edge case when `i - j == 0`, which means there is no previous tire. we should discard changeTime and compare `dp[i]` with `minimum[j]` directly.\n\n```python\ndef minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int:\n minimum = [] # minimum[i] represents for the min time to complete i + 1 laps without changing a tire\n total = [0] * len(tires)\n # the worst case is: fi = 1, ri = 2, changeTime = 10 ** 5\n # this while loop will be computed for at most math.ceil(math.log2(10 ** 5 + 1)) = 17 times\n while True:\n for t in range(len(tires)):\n total[t] += tires[t][0]\n tires[t][0] *= tires[t][1]\n minimum.append(min(total))\n # if the minimum cost is greater than changing a new tire, we stop looping\n if minimum[-1] > changeTime + minimum[0]: break\n\n # dp\n dp = [float(\'inf\')] * numLaps\n for l in range(numLaps):\n for pre in range(len(minimum)):\n if l - pre - 1 < 0:\n dp[l] = min(dp[l], minimum[pre])\n break\n dp[l] = min(dp[l], minimum[pre] + dp[l - pre - 1] + changeTime)\n return dp[-1]\n```\n\n
107,765
Minimum Time to Finish the Race
minimum-time-to-finish-the-race
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. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race.
Array,Dynamic Programming
Hard
What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values?
1,500
14
```\nclass Solution {\n public int minimumFinishTime(int[][] tires, int changeTime, int numLaps) {\n int[] minTime = new int[numLaps + 1];\n Arrays.fill(minTime, Integer.MAX_VALUE);\n for (int[] tire : tires) {\n checkMinTime(tire, minTime, changeTime, numLaps);\n }\n for (int i = 2; i <= numLaps; i++) {\n for (int j = 1; j < i; j++) {\n int remain = i % j;\n int currMin;\n\t\t\t\t// Greedy, in order to get the minimal runtime, we should repeat the same loop as much as possible.\n if (remain != 0) {\n currMin = (i / j) * (minTime[j] + changeTime) + minTime[remain];\n } else {\n\t\t\t\t\t// The last changeTime is not required if remain is 0\n currMin = (i / j) * (minTime[j] + changeTime) - changeTime; \n }\n minTime[i] = Math.min(minTime[i], currMin);\n }\n }\n\n return minTime[numLaps];\n }\n \n private void checkMinTime(int[] tire, int[] minTime, int changeTime, int numLaps) {\n int base = tire[0];\n int lap = 1;\n int curr = base;\n minTime[lap] = Math.min(minTime[lap], curr);\n int sum = base;\n\t\t// Greedy, if changeTime + base is smaller, the minimal runtime for the next lap\n\t\t// will not be better than minTime[lap - 1] + changeTime + minTime[1] \n while (curr * tire[1] - base <= changeTime && lap++ < numLaps) {\n curr *= tire[1];\n sum += curr;\n minTime[lap] = Math.min(minTime[lap], sum);\n }\n }\n}\n```
107,766
Minimum Time to Finish the Race
minimum-time-to-finish-the-race
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. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race.
Array,Dynamic Programming
Hard
What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values?
1,150
19
**Explanation**\n* Precompute a table, `f[i]`, the minimum time to complete `i` laps *without* and change.\n* Now the problem becomes: ***when do we change tires to minimise the total time?***\n\t* This is similar to the classic [Rod Cutting Problem]() from the CLRS textbook.\n\t* We just need to choose how many laps we do before the first change, `j`, and solve the remaining subproblem `dp[i - j]`\n\n```\ndp[i] = min(\n f[i], # no tire change\n min(f[j] + change_time + dp[i - j], for j < i) # change after the j first laps\n)\n```\n**Python**\n```python\nclass Solution:\n def minimumFinishTime(self, T, c, k):\n f = [ 10**9 for _ in range(k + 1) ]\n for t in T:\n lap_time = t[0]\n tot_time = t[0]\n for i in range(1, k + 1):\n f[i] = min(f[i], tot_time)\n lap_time *= t[1]\n tot_time += lap_time\n if tot_time > 10**9:\n break\n for i in range(2, k + 1):\n for j in range(1, i):\n f[i] = min(f[i], f[j] + c + f[i - j])\n return f[k]\n```\n\n**C++**\n```c++\nclass Solution {\npublic:\n int minimumFinishTime(vector<vector<int>>& T, int c, int k) {\n vector<int> f(k + 1, 1e9);\n for (auto &t : T) {\n long long lap_time = t[0];\n long long tot_time = t[0];\n for (int i = 1; i <= k; i++) {\n f[i] = min(f[i], (int) tot_time);\n if ((tot_time += (lap_time *= t[1])) > 1e9) {\n break;\n }\n }\n }\n for (int i = 2; i <= k; i++) {\n for (int j = 1; j < i; j++) {\n f[i] = min(f[i], f[j] + c + f[i - j]);\n }\n }\n return f[k];\n }\n};\n```
107,767
Minimum Time to Finish the Race
minimum-time-to-finish-the-race
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. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race.
Array,Dynamic Programming
Hard
What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values?
1,481
15
A intuition is that a tire will never be used for too many laps. Since r >= 2, 2^30 is already a very large number. So let\'s say, a tire will be used for 30 laps at most.\n\nLet best[i] = the minimal cost to run i laps.\nWe can initialize f[i] by using only a single tire. \nFor example, \nuse tire 0 for 1 laps: update best[1] with f0\nuse tire 0 for 2 laps, update best[2] with f0 * r0\n...\nuse tire 1 for 1 laps, update best[1] with f1\nuse tire 2 for 2 laps, update best[2] with f1 * r1\n...\n\nNow, the goal is to calculate all best[x] from 1 to numberLaps.\n\nSince the last tire can be used for 1 ~30 laps, we can iterate all the possibilities of best[x]:\nThe last tire run 1 lap: update best[x] with best[1] + best[x-1] + change\nThe last tire run 2 laps: update best[x] with best[2] + best[x-2] + change\n...\n\ncode:\n\n```\nclass Solution {\npublic:\n long long M = pow(10, 6);\n int minimumFinishTime(vector<vector<int>>& tires, int change, int laps) {\n vector<long long> best = vector<long long> (2000, pow(10, 10));\n best[0] = 0;\n for (auto t: tires) {\n long long cur = t[0];\n long long last = 0;\n for (int d = 1; d <= 30; d++ ) {\n best[d] = min(best[d], last + cur);\n last = last + cur;\n cur *= t[1];\n if (cur > M) break;\n } \n }\n for (long long d = 1; d <= laps; d++) {\n for (long long l = min(d, (long long)30); l >= 1; l --) {\n best[d] = min(best[d], best[l] + best[d - l] + change);\n }\n }\n return best[laps];\n }\n};\n```
107,768
Minimum Time to Finish the Race
minimum-time-to-finish-the-race
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. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race.
Array,Dynamic Programming
Hard
What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values?
679
7
# TL;DR\nThe final code is [here](#the-final-code). It is a top-down linear solution with memoization, that I think is more intuitive than most of the solutions posted here. It beats 95% of the solutions time-wise. The post elaborates on my way of thinking when working on this.\n\n# Introduction\nI suck at DP. When approaching a DP problem I always start with a top-down brute force recursive solution and then improve it by adding memoization. I don\'t even bother with the bottom-up approach. We\'ll do the same here. I found most of the solutions here to require some brilliant insight, and I don\'t appreciate that. I\'ll try to show you how I landed a solution with just using common sense.\n\n# Start with brute force\nThe algorithm needs to optimally make the following two decisions again and again until there are no more laps left in the race:\n- Which tire to select?\n- For how many laps do we keep the selected tire?\n\nSee below the code that implements this in a brute force manner:\n```cpp\nint MinFinishTime(const vector<vector<int>>& tires, int laps, int change_time,\n bool is_first_lap = true) {\n if (laps == 0) {\n return 0;\n }\n int result = numeric_limits<int>::max();\n // When we start the race the first tire is "free" to put on.\n int c = is_first_lap ? 0 : change_time;\n for (auto& t : tires) {\n // Try a tire.\n int time_with_tire = 0;\n for (int lap_time = t[0], remaining_laps = laps; remaining_laps > 0;\n lap_time *= t[1], --remaining_laps) {\n // Keep tire for consecutive laps, then change tire by a recursive call\n // after each lap.\n time_with_tire += lap_time;\n result = min(c + time_with_tire + MinFinishTime(tires, remaining_laps - 1,\n change_time, false),\n result);\n }\n }\n return result;\n}\n```\nOnce we selected our tire (outer foreach loop), we try to keep it for the remaining laps (inner for loop). After each lap with the same tire we try to change to a new one, and continue the race for the remaining laps (recursive call). We\'ll bubble up the minimum from each recursive call. The minimum of minimums will be the answer.\n\nThis code is obviously going to TLE, but even before that it will produce some integer overflows, so let\'s get rid of that first.\n\nThe `lap_time` variable will grow exponentially as we keep taking laps with the same tire. It can quickly get out of the 32 bit integer range if `t[1]` is large. For a moment let\'s assume we have a single tire type available. It doesn\'t make sense to keep the tire when `lap_time` is greater or equal `change_time + t[0]` (or $$f*r^0 = f*1$$ as per the problem statement). It\'s not hard to see that this also applies if we have multiple tires, so let\'s add this to our loop condition:\n\n```cpp\nfor (int lap_time = t[0], remaining_laps = laps;\n remaining_laps > 0 && lap_time < change_time + t[0];\n lap_time *= t[1], --remaining_laps) { /* ... */ }\n```\nStill, this algorithm is of exponential time complexity, and will TLE even for early test cases. We\'ll work on improving on this in the following sections.\n\n# Add memoization\nNotice that `laps` is the only parameter of `MinFinishTime` that changes throughout the recursive calls (`is_first_lap` doesn\'t matter as it\'s always `false` except for the topmost call). This makes the function a good candidate for 1-dimensional memoization. In general, when you do top-down DP you should be aiming for minimizing the variables in the parameter set of your recursive function, because that\'s what fundamentally defines how effective your memoization will be.\n\nThe code below adds memoization to the brute force recursive solution. We save the results from previous calls in a `vector<int>` that is of size `laps` initialized to all `-1`\'s.\n\n```cpp\nint MinFinishTime(const vector<vector<int>>& tires, int laps, int change_time,\n vector<int>& memo, bool is_first_lap = true) {\n if (laps == 0) {\n return 0;\n }\n if (memo[laps - 1] != -1) {\n // We have already computed the optimal solution for racing this number\n // of laps.\n return memo[laps - 1];\n }\n int result = numeric_limits<int>::max();\n // When we start the race the first tire is "free" to put on.\n int c = is_first_lap ? 0 : change_time;\n for (auto& t : tires) {\n // Try a tire.\n int time_with_tire = 0;\n for (int lap_time = t[0], remaining_laps = laps;\n remaining_laps > 0 && lap_time < change_time + t[0];\n lap_time *= t[1], --remaining_laps) {\n // Keep tire for consecutive laps, then change tire by a recursive call\n // after each lap.\n time_with_tire += lap_time;\n result = min(c + time_with_tire + MinFinishTime(tires, remaining_laps - 1,\n change_time, memo, false),\n result);\n }\n }\n return memo[laps - 1] = result;\n}\n```\nI was very disappointed when this code TLE\'d on the late test cases. Let\'s examine the time complexity here:\n- The `MinFinishTime` function will run `laps` times in total thanks to the memoization.\n- Within the function we\'ll loop over `tires`.\n- Within the loop on `tires` we try to take consecutive laps with the same tire.\n\nIt\'s worth thinking about the maximum number of consecutive laps with the same tire. As per the problem definition the following conditions hold:\n\n- `t[0] >= 1`\n- `t[1] >= 2`\n- `change_time <= 100000`\n\nIf we consider the extreme case when `t[0]` and `t[1]` is minimal and `change_time` is maximal, we see that we can run at most 16 laps with the same tire because we anyways change tires when `lap_time >= change_time + t[0]`. Since $$log_2 (10^5+1) = 16.6$$ we\'ll never take more than 16 laps with the same tire. This leaves with us $$O(L*T*16)=O(L*T)$$ time complexity (where $$L$$ is the number of laps and $$T$$ is the number of tires). It seems though it is not good enough, so we have to work a bit more. The 1-dimensional search space here hints us that we can somehow land a linear algorithm. \n\n# Go linear\n\nWe can use our intuition to see that we can\'t save ourselves from trying all the `laps` so we\'ll have to get rid of the loop on `tires` somehow to reduce time complexity. Let\'s examine the loop:\n\n```cpp\nfor (auto& t : tires) {\n int time_with_tire = 0;\n for (int lap_time = t[0], remaining_laps = laps;\n remaining_laps > 0 && lap_time < change_time + t[0];\n lap_time *= t[1], --remaining_laps) {\n // Keep tire for consecutive laps, then change tire by a recursive call\n // after each lap.\n time_with_tire += lap_time;\n result = min(c + time_with_tire + MinFinishTime(tires, remaining_laps - 1,\n change_time, memo, false),\n result);\n }\n}\n```\nNotice that the inner loop is nothing more than a rolling sum on `lap_time`. The `laps` parameter only determines the number of iterations, it doesn\'t affect the sum itself (i.e., `time_with_tire`) in any way. We could precompute this rolling sum for all tires and store it in a 2-dimensional array `precomputed_time_with_tire`:\n```cpp\nfor (int i = 0; i < tires.size(); ++i) {\n int attempts = min((int)precomputed_time_with_tire[i].size(), laps);\n for (int j = 0; j < attempts; ++j) {\n int remaining_laps = laps - j;\n int time_with_tire = precomputed_time_with_tire[i][j];\n result = min(c + time_with_tire +\n MinFinishTime(tires, remaining_laps - 1, change_time,\n precomputed_time_with_tire, memo, false),\n result);\n }\n}\n```\nNote that the time complexity remains the same. However we can make a key observation: `c + MinFinishTime(...)` doesn\'t depend on `i` (the current tire) at all, it only depends on `remaining_laps` AKA `laps - j`. To minimize `time_with_tire + c + MinFinishTime(...)` it\'s enough to consider the minimum `i` for `precomputed_time_with_tire[i][j]` for all `j`\'s. We don\'t care about the `i`\'s for a particular `j` when `precomputed_time_with_tire[i][j]` is not minimal. Following this logic you can reduce the dimensionality of the precomputed rolling sum to 1 and get rid of the outer loop:\n```cpp\nfor (int i = 0; i < min((int)min_time_with_tire.size(), laps); ++i) {\n result = min(c + min_time_with_tire[i] +\n MinFinishTime(tires, laps - i - 1, change_time,\n min_time_with_tire, memo, false),\n result);\n}\n```\n\nHere `min_time_with_tire` is a 1-dimensional array that holds the precomputed minimum value for each `j` from `precomputed_time_with_tire[i][j]`.\n\nIntuitively, you can think about `precomputed_time_with_tire[i][j]` as a plot of functions $$g_i(j) = f_i * r_i^j$$. However `min_time_with_tire[j]` only stores the minimum $$g_i(j)$$ for each $$j$$.\n\nAfter these amendments the code is of $$O(L*16)=O(L)$$ time complexity, and passes all the test cases. The space complexity is $$O(L+16)=O(L)$$. We beat 95% of the solutions time-wise.\n\n# The final code\n\n```\nint MinFinishTime(const vector<vector<int>>& tires, int laps, int change_time,\n const vector<int>& min_time_with_tire, vector<int>& memo,\n bool is_first_lap = true) {\n if (laps == 0) {\n return 0;\n }\n if (memo[laps - 1] != -1) {\n return memo[laps - 1];\n }\n int result = numeric_limits<int>::max();\n int c = is_first_lap ? 0 : change_time;\n for (int i = 0; i < min((int)min_time_with_tire.size(), laps); ++i) {\n result = min(c + min_time_with_tire[i] +\n MinFinishTime(tires, laps - i - 1, change_time,\n min_time_with_tire, memo, false),\n result);\n }\n return memo[laps - 1] = result;\n}\n\nclass Solution {\n public:\n int minimumFinishTime(vector<vector<int>>& tires, int change_time, int laps) {\n vector<int> min_time_with_tire;\n for (auto& t : tires) {\n int lap_time = t[0];\n int time_with_tire = 0;\n for (int lap = 0; lap < laps; ++lap) {\n time_with_tire += lap_time;\n if (lap == min_time_with_tire.size()) {\n min_time_with_tire.push_back(time_with_tire);\n } else {\n min_time_with_tire[lap] =\n min(time_with_tire, min_time_with_tire[lap]);\n }\n if (lap_time > (t[0] + change_time) / t[1]) {\n break;\n }\n lap_time *= t[1];\n }\n }\n vector<int> memo(laps, -1);\n return MinFinishTime(tires, laps, change_time, min_time_with_tire, memo);\n }\n};\n```
107,773
Minimum Time to Finish the Race
minimum-time-to-finish-the-race
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. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race.
Array,Dynamic Programming
Hard
What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values?
474
7
Bottom up dp - for each lap i, see if we get optimal time by changing tires in lap j before it ie dp[i] = Math.min (dp[i], dp[j] + changeTime + dp[i - j]) \n\n```\n public int minimumFinishTime(int[][] tires, int changeTime, int numLaps) {\n \n //Min time to finish all laps without changing tires, compared across all tires\n int[] minTimes = new int[numLaps +1];\n Arrays.fill(minTimes, Integer.MAX_VALUE);\n for(int[] tire: tires ){\n populateMinTime(minTimes, tire , changeTime, numLaps);\n }\n \n\t\t//For every lap i , see if you get better time by changing tires on all laps before i ie 1 to i using j loop\n\t\t//eg : for lap 10, check if you get better time by changing tire at all laps before 10 ie 1.2.3....9\n for(int i=1; i<=numLaps; i++){\n for(int j=1; j<i; j++){\n minTimes[i] = Math.min( minTimes[i], minTimes[j] + changeTime + minTimes[i-j]);\n } \n }\n return minTimes[numLaps];\n }\n \n void populateMinTime(int[] minTimes, int[] tire, int changeTime, int numLaps){\n \n int baseTime = tire[0];\n int expTime = tire[1];\n \n //To keep track of a lap time & entire race time using this tire\n int lapTime = baseTime;\n int totalTime = lapTime;\n \n //lap 1 will only have base time, calculate from lap 2\n minTimes[1] = Math.min(baseTime, minTimes[1]);\n for(int lap=2; lap<=numLaps; lap++){\n \n lapTime*=expTime; //time for current lap = prevLapTime*expTime instead of recalcuating entire value\n \n //***IMP change time is better, no point calculating further\n if(lapTime> changeTime+baseTime) break; \n \n totalTime+=lapTime;\n \n minTimes[lap] = Math.min(minTimes[lap], totalTime);\n } \n }
107,778
Minimum Time to Finish the Race
minimum-time-to-finish-the-race
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. You are also given an integer changeTime and an integer numLaps. The race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds. Return the minimum time to finish the race.
Array,Dynamic Programming
Hard
What is the maximum number of times we would want to go around the track without changing tires? Can we precompute the minimum time to go around the track x times without changing tires? Can we use dynamic programming to solve this efficiently using the precomputed values?
601
5
The idea: calculate the max number it makes sense to use the same tire. In other posts, posters use the number 18 because `2^18` > the constraint `2^18 > changeTime <= 10^5`. Here we calculate the actual best number.\n\nImagine a tire [2, 3] and changeTime 30\nIf we use the same tire\nAt lap 1: cost is 2\nLap 2: cost is 2 * 3^1 = 6\nLap 3: cost is 2 * 3^2 = 18\nLap 4: cost is 2 * 3^3 = 54 -> here it would not make sense to use the same tire because we can just change the tire here for cost of 30 and then use the new tire for cost of 2, so we figure out the max consecutive laps we can use this tire for is 3\n\nIn the code below, we figure out how many times we can use the same tire for ANY tire, by calculating it based on the smallest tire in the tire list.\n\n`sameTire` is a DP array tracking what is the min cost to complete lap `i` if we use one single tire (any tire)\n\n```\nvar minimumFinishTime = function(tires, changeTime, numLaps) { \n const n = tires.length\n const smallestTire = Math.min(...tires.map(t => t[1]))\n const maxSameTire = Math.floor(Math.log(changeTime) / Math.log(smallestTire)) + 1\n const sameTireLast = Array(n).fill(0)\n\t\n\t// DP array tracking what is the min cost to complete lap i using same tire\n const sameTire = Array(maxSameTire + 1).fill(Infinity)\n for (let lap = 1; lap <= maxSameTire; lap++) {\n tires.forEach((tire, i) => {\n sameTireLast[i] += tire[0] * tire[1] ** (lap - 1)\n sameTire[lap] = Math.min(sameTire[lap], sameTireLast[i])\n })\n }\n \n const dp = Array(numLaps + 1).fill(Infinity)\n for (let i = 1; i < numLaps + 1; i++) {\n if (i <= maxSameTire) dp[i] = sameTire[i]\n\t\t// at each lap, we can either use the same tire up to this lap (sameTire[i])\n\t\t// or a combination of 2 different best times, \n\t\t// eg lap 6: use best time from lap 3 + lap 3\n\t\t// or from lap 4 + lap 2\n\t\t// or lap 5 + lap 1\n for (let j = 1; j < i / 2 + 1; j++) {\n dp[i] = Math.min(dp[i], dp[i-j] + changeTime + dp[j])\n }\n }\n return dp[numLaps]\n};\n```
107,781
Count Integers With Even Digit Sum
count-integers-with-even-digit-sum
Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits.
Math,Simulation
Easy
Iterate through all integers from 1 to num. For any integer, extract the individual digits to compute their sum and check if it is even.
5,133
79
We calculate the sum, and then apply formula (**we just need to check if the sum is even or odd**) to calculate the final answer. \nI got the idea while checking the given examples in the description. Just try to check what will be the ouptut for 10, 20, 30, 40 etc:\n10 = 2, 4, 6, 8 (4)\n20 = 2, 4, 6, 8, 11, 13, 15, 17, 19, 20 (10)\n30 = 2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28. (14)\n...\n```\nclass Solution {\npublic:\n int countEven(int num) {\n int temp = num, sum = 0;\n while (num > 0) {\n sum += num % 10;\n num /= 10;\n }\n return sum % 2 == 0 ? temp / 2 : (temp - 1) / 2;\n }\n};\n```
107,823
Count Integers With Even Digit Sum
count-integers-with-even-digit-sum
Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits.
Math,Simulation
Easy
Iterate through all integers from 1 to num. For any integer, extract the individual digits to compute their sum and check if it is even.
2,332
23
See my latest update in repo [LeetCode]()\n\n\n## Solution 1.\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(NlgN)\n// Space: O(1)\nclass Solution {\npublic:\n int countEven(int num) {\n int ans = 0;\n for (int i = 1; i <= num; ++i) {\n int n = i, sum = 0;\n while (n) {\n sum += n % 10;\n n /= 10;\n }\n ans += sum % 2 == 0;\n }\n return ans;\n }\n};\n```\n\n## Solution 2. Pattern Finding\n\n`num` | 1 |2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|\n--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--\ndigit sum |1|2|3|4|5|6|7|8|9|1|2|3|4|5|6|7|8|9|10|2|3|4|5|6|7\ndigit sum is even|0|1|0|1|0|1|0|1|0|0|1|0|1|0|1|0|1|0|0|1|0|1|0|1|0\nanswer |0|1|1|2|2|3|3|4|4|4|5|5|6|6|7|7|8|8|9|10|10|11|11|12|12|\n\n\nThe answer increments when the digit sum of `num` is even.\n\nWe can see that the answer is somewhat related to `num / 2` and `digitSum(num) % 2`. It turns out to be `(num - digitSum(num) % 2) / 2`.\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(lgN)\n// Space: O(1)\nclass Solution {\npublic:\n int countEven(int num) {\n int sum = 0, tmp = num;\n while (num) {\n sum += num % 10;\n num /= 10;\n }\n return (tmp - sum % 2) / 2;\n }\n};\n```
107,831
Count Integers With Even Digit Sum
count-integers-with-even-digit-sum
Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits.
Math,Simulation
Easy
Iterate through all integers from 1 to num. For any integer, extract the individual digits to compute their sum and check if it is even.
3,941
28
**Brute force**:\nIterate through all the numbers from 1 to num inclusive and check if the sum of the digits of each number in that range is divisible by 2. \n<iframe src="" frameBorder="0" width="670" height="280"></iframe>\n\n\n**Observation**:\n```\nIntegers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]\nSums: [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6]\nSum is Even? : [0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1]\nCount(Even sums): [0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 10, 10, 11, 11, 12] \n```\nFor a `num` with even sum of its digits, count of Integers With Even Digit Sum less than or equal to `num` is `num`/2\nFor a `num` with odd sum of its digits, count of Integers With Even Digit Sum less than or equal to `num` is (`num`-1)/2\n\n**Optimized solution:**\n<iframe src="" frameBorder="0" width="830" height="190"></iframe>\n
107,835
Count Integers With Even Digit Sum
count-integers-with-even-digit-sum
Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits.
Math,Simulation
Easy
Iterate through all integers from 1 to num. For any integer, extract the individual digits to compute their sum and check if it is even.
1,470
9
### We sum the digits of num.\n\n##### if the sum is **even** -> return num // 2\n##### if the sum is **odd** -> return (num - 1) // 2\n\n```\nclass Solution:\n def countEven(self, num: int) -> int:\n return num // 2 if sum([int(k) for k in str(num)]) % 2 == 0 else (num - 1) // 2\n```\n\t\t\n\t\t\n##### Since 1 <= num <= 1000 we will sum at most **4 digits**, hence the solution is **O(1)**.
107,836
Count Integers With Even Digit Sum
count-integers-with-even-digit-sum
Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits.
Math,Simulation
Easy
Iterate through all integers from 1 to num. For any integer, extract the individual digits to compute their sum and check if it is even.
2,466
19
1. Edit: Easier Explanation:\n\t// Numbers\n **1, 2,** 3, 4, **5, 6**, 7, 8, **9, 10**, 11, 12, **13, 14**, 15, 16, **17, 18**, 19, 20, **21, 22**...\n\t// Digit sums, 1 represents odd and 0 represents even\n\t**1, 0,** 1, 0, **1, 0**, 1, 0, **1, 1,** 0, 1, **0, 1,** 0, 1, **0, 1,** 0, 0, **1, 0**...\n \n\tFor any two adjacent numbers, the digit sum of one of them is even, another is odd except when an number % 10 == 0 (parities flip every 10 numbers). So the answer to this question is either num / 2 or (num - 1) / 2. Looking at the squence above, for every digit sum is odd (1), the answer is always (num - 1) / 2 (e.g. 14, 21) and for every digit sum is even (0), the answer is always num / 2. So we only need to check the digit sum of the last number.\n\t\n\tOptimized answer with bit opration, based on @Eleet_6IX\'s optimization\n\t```\n\tpublic int countEven(int num) {\n\t\t// Digit sum of the last number, we can get each digit this way sicne the range is [1, 1000]\n\t\tint sum = num % 10 + (num / 10) % 10 + (num / 100) % 10 + (num / 1000) % 10;\n\n\t\t// Check the parity of the digit sum of the last number\n\t\treturn (num - (sum & 1)) / 2;\n\t}\n\t```\n\n\n2. Original explaination and answer:\n\tFor every number % 10 != 0, its digit sum will always be the digit sum of its previous number + 1.\n\tFor every number % 10 == 0, its digit sum will always has the same parity with the digit sum of its previous number. e.g. 879 and 880, 8 + 7 + 9 = 24, 8 + 8 + 0 = 16\n\n\tSo the order of parity reverts every 10 numbers.\n\tAnd The answer to this question is either num / 2 or (num - 1) / 2.\n\n\tYou only need to check if both of the last number and the digits sum of the last number are even.\n\n\tI feel there\'re better answers but this\'s the best I can come up with during the contest.\n\n\t```\n\tpublic int countEven(int num) {\n\t\t// Digit sum of the last number, we can get each digit this way sicne the range is [1, 1000]\n\t\tint sum = num % 10 + (num / 10) % 10 + (num / 100) % 10 + (num / 1000) % 10;\n\n\t\t// Check if the last number and its digit sum are even\n\t\treturn (num - 1) / 2 + (sum % 2 == 0 && num % 2 == 0 ? 1 : 0);\n\t}\n\t```
107,837
Count Integers With Even Digit Sum
count-integers-with-even-digit-sum
Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits.
Math,Simulation
Easy
Iterate through all integers from 1 to num. For any integer, extract the individual digits to compute their sum and check if it is even.
1,218
8
Just for fun. We iterating through each position and track sum of digits as we go.\n\n**Python 3**\n```python\nclass Solution:\n def countEven(self, num: int) -> int:\n def count(n: int, sum_n: int, pos: int):\n if pos == 0:\n return sum_n % 2 == 0\n return sum(count(n + i * pos, sum_n + i, pos // 10) for i in range(10) if n + i * pos <= num)\n return count(0, 0, 100) - 1\n```\n
107,841
Count Integers With Even Digit Sum
count-integers-with-even-digit-sum
Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits.
Math,Simulation
Easy
Iterate through all integers from 1 to num. For any integer, extract the individual digits to compute their sum and check if it is even.
558
8
```\nclass Solution {\npublic:\n int countEven(int num) \n {\n /* \n Here we have alternate digit sum as odd and even i.e.\n if sum of digits sum of num -> even \n then sum of digit sum of num+1 -> odd \n \n and vice versa \n \n AND\n \n if sum of each digit in num is even then res -> num/2\n \n else res -> (num-1)/2\n \n */\n \n int currSum = 0; // for storing sum of each digit in num \n \n int store = num; // storing value of num for further checking\n \n while(num)\n {\n currSum += num % 10; \n num /= 10;\n }\n \n if(currSum & 1) // i.e. sum is odd\n return (store-1)/2;\n \n else\n return store/2;\n \n }\n};\n```
107,842
Count Integers With Even Digit Sum
count-integers-with-even-digit-sum
Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits.
Math,Simulation
Easy
Iterate through all integers from 1 to num. For any integer, extract the individual digits to compute their sum and check if it is even.
690
6
Intuition here is that numbers have digitSum even and odd consecutively\n\n0 1 2 3 4 5 6 7 8 9 => 4 numbers with digit sum as even (all even numbers)\n10 11 12 13 14 15 16 17 18 19 => 5 numbers with digit sum as even 11, 13, 15, 17, 19 (all odd numbers)\n20 21 22 23 24 25 26 27 28 29 => 5 numbers with digit sum as even 20, 22, 24, 26, 28 (all even numbers)\n30 31 32 33 34 35 36 37 38 39 => 5 numbers with digit sum as even 31, 33, 35, 37, 39 (all odd numbers)\n\n**So the evens can be given as num//2 in all the cases except when the number itself is even but digit sum is odd**. Example:10, 12, 30\nIn such cases the even numbers would less by 1 as that particular number is not a valid number.\n\n```python\n def countEven(self, num: int) -> int:\n n, dSum = num, 0\n while n > 0: # Calculate digit sum of numbers\n dSum += n%10\n n = n//10\n if num % 2 == 0 and dSum % 2 == 1:\n return num//2 - 1\n return num//2\n```
107,844
Count Integers With Even Digit Sum
count-integers-with-even-digit-sum
Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits.
Math,Simulation
Easy
Iterate through all integers from 1 to num. For any integer, extract the individual digits to compute their sum and check if it is even.
679
9
Implementation\n\n**Brute Force Approach\nTime Complexity: O(NLogN)\nSpace Complexity: O(1)\nIdea: traversing from 1 to num, and generating the sum of the digits of each num, and checking whether they are even or odd, and counting**\n\n```\nclass Solution {\npublic:\n \n // generating the sum of the digits of the number, if the sum is even return true, otherwise return false\n bool numIsEven(int num){\n int sum = 0;\n while(num){\n sum += num%10;\n num /= 10;\n }\n if(sum%2) return false;\n return true; \n }\n \n int countEven(int num) {\n int cnt = 0; \n // traversing from 1 to num, and generating the sum of the digits of each number, and checking whether they are even or odd\n for(int itr = 1; itr <= num; itr++){\n if(numIsEven(itr)) cnt++;\n }\n return cnt;\n }\n};\n```\n\n\n**Optimal Approach\nTime Complexity: O(LogN)\nSpace Complexity: O(1)**\n\n**Idea: Observe this pattern** \n```\n1) num = 6 = [2,4,6] => 3\n2) num = 10 = [2,4,6,8] => 4\n3) num = 15 = [2,4,6,8,11,13,15] => 7\n4) num = 20 = [2,4,6,8,11,13,15,17,19,20] => 10\n5) num = 27 = [2,4,6,8,11,13,15,17,19,20,22,24,26] => 13\n```\n\nFrom this pattern we can observe one thing, if we are taking the sum of the digits of the num, and if that sum is even then we can directly divide our num by 2, and return the result, but if our sum if odd then we need to do (num-1)/2 to get the desired results.\n\n```\nclass Solution {\npublic:\n int countEven(int num) {\n \n // creating a backup of num to use it later\n int numBackup = num;\n \n // generating the sum of the digits of the num\n int sum = 0;\n while(num){\n sum += num%10;\n num /= 10;\n }\n \n // if sum is odd, return (numBackup-1)/2 as per the pattern we found\n if(sum%2) return (numBackup-1)/2;\n \n // if sum is even, return numBackup/2\n else return numBackup/2;\n }\n};\n```\nIf you find any issue in understanding the solution then comment below, will try to help you.\nIf you found my solution useful.\nSo **please do upvote and encourage me** to document all leetcode problems\uD83D\uDE03\nHappy Coding :)
107,847
Count Integers With Even Digit Sum
count-integers-with-even-digit-sum
Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits.
Math,Simulation
Easy
Iterate through all integers from 1 to num. For any integer, extract the individual digits to compute their sum and check if it is even.
1,416
6
# Code\u2705\n```\nclass Solution:\n def countEven(self, num: int) -> int:\n count = 0\n for i in range(2,num+1):\n if sum(list(map(int, str(i).strip()))) % 2 == 0:\n count +=1\n return count\n```
107,849
Count Integers With Even Digit Sum
count-integers-with-even-digit-sum
Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits.
Math,Simulation
Easy
Iterate through all integers from 1 to num. For any integer, extract the individual digits to compute their sum and check if it is even.
972
5
# Code\n```\nclass Solution {\n public int countEven(int a) {\n int count = 0,sum = 0,r = 0,c_num = 0;\n for (int i = 1; i <= a; i++) {\n c_num = i;// c_num = current value;\n while (c_num != 0) {\n r = c_num % 10;// r = reminder\n sum = sum + r;\n c_num = c_num / 10;\n }\n if(sum % 2 == 0) count++;\n sum = 0;\n }\n return count;\n }\n}\n```
107,852
Count Integers With Even Digit Sum
count-integers-with-even-digit-sum
Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even. The digit sum of a positive integer is the sum of all its digits.
Math,Simulation
Easy
Iterate through all integers from 1 to num. For any integer, extract the individual digits to compute their sum and check if it is even.
213
5
```\nclass Solution {\npublic:\n\xA0\xA0\xA0 int countEven(int num) {\n// cnt variable keeps a record of total sum of digits which are even \n\n\xA0\xA0\xA0\xA0\xA0 int\xA0 cnt = 0\xA0 ;\n// Now, using a for loop to iterate till the num\n// We can also directly start i = 2 as it\'s the first even number \n\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0 for ( int i = 1 ; i<= num ;i++)\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0 { \n// s keeps the sum of digits\n// e keeps original i \n\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0 int\xA0 e = i , s=0\xA0 ;\n// Now, finding sum of digits using a while loop till (e > 0)\xA0\xA0\xA0 .\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0 \n\xA0\xA0\xA0\xA0\xA0\xA0\xA0 while (e)\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0 {\n// it gives last digits of a number\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0 int r = e %10 ; \n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0 s=s+r ; \n// It decreases the number so that we can find other digits as well\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0 e/=10;\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0 }\n\xA0 // Now, if s is even it will be divisible by 2 and we will increment cnt\xA0 \n\xA0\xA0\xA0\xA0 \n\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0 if( s%2 == 0 )\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0\xA0 cnt ++;\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0 }\n\xA0\xA0\xA0\xA0 return cnt ; \n\xA0\xA0\xA0 }\n};\n\n```
107,857
Merge Nodes in Between Zeros
merge-nodes-in-between-zeros
You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0. For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's. Return the head of the modified linked list.
Linked List,Simulation
Medium
How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes across a ‘0’. In that case, the modifying pointer is incremented to modify the next node. Do not forget to have the next pointer of the final node of the modified list point to null.
8,490
78
For these modification Questions , **Recursion** is a great tool in these linked list question.\n\n**My Intuition** :\nWhenever `the process is having repeated tasks again and again especially in Linked List`, We use **Recursion**.\n# For eg -> \n```\n1. Skip M nodes, delete N nodes nodes\n2. Reverse every K nodes.\n3. Skip M node, Reverse N nodes.\n4. get sum between consecutive 0\'s.{This Question}.\n```\n\nYou see all above question are having **same tasks again and again**, and thats why **I thought of Recursion**.\n \n\n**Algorithm**: In Recursion , we only have to consider about first part and rest will be done by principle of recursion.\n1. Fetch the sum between two consecutive 0.\n2. Assign the sum to first node between 2 consecutive 0\'s.\n3. Call function for the next parts.\n4. Whatever was returned from the function , assign it to next of the first node on which we assigned the sum previously.\n5. Return the New head as head->next.\n\n**We are using Constant space because we are not creating any extra node for sum.**\n**We are just assigning the sum to already existed node.**\n# C++ Recursive : Very Easy\n ListNode* mergeNodes(ListNode* head){\n\t //BASE CASE -> if we have a single zero, simply return null\n if(!head->next) return nullptr;\n \n //fetch sum from current 0 to next 0\n ListNode* ptr= head->next;\n int sum=0;\n while(ptr->val!=0) sum+= ptr->val, ptr=ptr->next;\n \n //assign sum on the first node between nodes having value 0.\n head->next->val= sum;\n \n //call and get the answer and connect the answer to next of head->next\n head->next->next= mergeNodes(ptr);\n \n //return head->next..=> new head\n return head->next;\n }\n**Time**: O(N).\n**Space**: O(1) {Excluding recursion space}.\n\n\t\n# C++ Iterative :\tFaster than 95%\nSame as Recursive above but in iterative version.\nDoing everything INPLACE without creating new node for sum, as in recursion.\n \n ListNode* mergeNodes(ListNode* head) {\n head=head->next;\n ListNode* start=head;\n while(start){\n\t\t ListNode* end= start; /* Point to first node of current part for getting sum */\n int sum=0;\n while(end->val!=0) sum+= end->val , end=end->next;\n start->val=sum; /*assign sum to first node between two 0*/\n start->next=end->next; /*make this connect to first node of next part*/\n start=start->next; /*go..to..next..part*/\n\t\t }\n return head;\n }\n\n**Time** -> O(N)\n**Space** -> O(1) {We are doing everything **inplace**, **without creating new nodes for sum**}\n\n\n
107,876
Merge Nodes in Between Zeros
merge-nodes-in-between-zeros
You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0. For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's. Return the head of the modified linked list.
Linked List,Simulation
Medium
How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes across a ‘0’. In that case, the modifying pointer is incremented to modify the next node. Do not forget to have the next pointer of the final node of the modified list point to null.
3,454
36
Understanding:\nIterate through the list and keep adding the digits till you find a \'0\'. When you find a \'0\' add it to the list and repeat the process again.\n\nAlgorithm:\n- Initialize sum = 0, pointer 1 to the head and pointer 2 to the next element in the list.\n- Loop through the list till pointer 2 reaches the end of the list.\n- In the loop, if pointer 2\'s value is 0 then, make pointer 1 move to the next list item and give it the value of the current sum. Re-initialize the sum to 0.\n- Else keep adding pointer 2\'s value to the current sum.\n- Increment pointer 2.\n- When pointer 2 reaches the end of the list, make pointer 1\'s next None. (We store the sum values in the same list to make it memory efficient)\n- Return the second element on the list. (First element is a 0)\n\n```\nclass Solution:\n def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n ptr1 = head\n ptr2 = head.next\n s = 0\n while ptr2:\n if ptr2.val == 0:\n ptr1 = ptr1.next\n ptr1.val=s\n s=0\n else:\n s+=ptr2.val\n ptr2 = ptr2.next\n ptr1.next=None\n return head.next\n```
107,889
Merge Nodes in Between Zeros
merge-nodes-in-between-zeros
You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0. For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's. Return the head of the modified linked list.
Linked List,Simulation
Medium
How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes across a ‘0’. In that case, the modifying pointer is incremented to modify the next node. Do not forget to have the next pointer of the final node of the modified list point to null.
4,560
34
**C++**\n```cpp\nListNode* mergeNodes(ListNode* head) {\n for (auto *p_z = head, *p = head->next; p != nullptr; p = p->next) {\n if (p->val != 0)\n p_z->val += p->val;\n else {\n p_z->next = p->next != nullptr ? p : nullptr;\n p_z = p;\n }\n }\n return head;\n}\n```
107,892
Merge Nodes in Between Zeros
merge-nodes-in-between-zeros
You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0. For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's. Return the head of the modified linked list.
Linked List,Simulation
Medium
How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes across a ‘0’. In that case, the modifying pointer is incremented to modify the next node. Do not forget to have the next pointer of the final node of the modified list point to null.
744
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTake loop for iteration .While iterating increment the count variable when your pointer points to 0. When you find two consecutive zero\'s add the inbetween node val in sum variable. At last add your sum into new ListNode and return it.\n\n# Complexity\n- Time complexity:\n**O(N)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n **O(N)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeNodes(ListNode head) {\n ListNode ans=new ListNode();\n ListNode temp=ans;\n ListNode curr=head;\n int sum=0;\n int count=0;\n while(curr!=null){\n if(curr.val==0) count++;\n else sum+=curr.val;\n\n if(count==2){\n ListNode node=new ListNode(sum);\n ans.next=node;\n ans=ans.next;\n sum=0;\n count=1;\n }\n curr=curr.next;\n }\n return temp.next;\n }\n}\n```
107,893
Merge Nodes in Between Zeros
merge-nodes-in-between-zeros
You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0. For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's. Return the head of the modified linked list.
Linked List,Simulation
Medium
How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes across a ‘0’. In that case, the modifying pointer is incremented to modify the next node. Do not forget to have the next pointer of the final node of the modified list point to null.
569
5
Pls upvote if u like it\n\n```\npublic ListNode mergeNodes(ListNode head) {\n ListNode cur;\n ListNode res = new ListNode(-1);\n cur = res;\n int sum = 0;\n\n while (head != null) {\n if (head.val != 0) {\n sum += head.val;\n } else {\n cur.next = new ListNode(sum);\n cur = cur.next;\n sum = 0;\n }\n head = head.next;\n }\n return res.next.next;\n}\n\n```
107,897
Merge Nodes in Between Zeros
merge-nodes-in-between-zeros
You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0. For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's. Return the head of the modified linked list.
Linked List,Simulation
Medium
How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes across a ‘0’. In that case, the modifying pointer is incremented to modify the next node. Do not forget to have the next pointer of the final node of the modified list point to null.
1,277
13
class Solution {\npublic:\n\n ListNode* mergeNodes(ListNode* head) {\n if(head->val==0){\n head=head->next;\n }\n ListNode* res=head;\n ListNode* temp=head;\n int sum=0;\n \n while(temp){\n if(temp->val!=0){\n sum+=temp->val;\n temp=temp->next;\n } \n else{\n res->val=sum;\n res->next = temp->next;\n temp = temp->next;\n res = temp;\n sum = 0;\n }\n \n }\n return head;\n }\n};
107,901
Merge Nodes in Between Zeros
merge-nodes-in-between-zeros
You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0. For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's. Return the head of the modified linked list.
Linked List,Simulation
Medium
How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes across a ‘0’. In that case, the modifying pointer is incremented to modify the next node. Do not forget to have the next pointer of the final node of the modified list point to null.
2,790
15
```\nclass Solution {\npublic:\n ListNode* mergeNodes(ListNode* head) {\n ListNode* res = new ListNode(0);\n ListNode* ret = res;\n int sm = 0;\n head = head->next;\n \n while(head != NULL){\n if(head->val == 0){\n res->next = new ListNode(sm);\n res = res->next;\n sm = 0;\n } else {\n sm += head->val;\n }\n head = head->next;\n }\n \n return ret->next;\n }\n};\n```
107,902
Merge Nodes in Between Zeros
merge-nodes-in-between-zeros
You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0. For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's. Return the head of the modified linked list.
Linked List,Simulation
Medium
How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes across a ‘0’. In that case, the modifying pointer is incremented to modify the next node. Do not forget to have the next pointer of the final node of the modified list point to null.
5,558
21
Use zero nodes to store the sum of merged nodes, remove the last zero node, which is unused.\n\n1. Use `prev` to connect and move among all zero nodes;\n2. Use `head` to traverse nodes between zero nodes, and add their values to the previous zero node;\n3. Always use `prev` point to the node right before current zero node, hence we can remove the last zero node easily.\n\n```java\n public ListNode mergeNodes(ListNode head) {\n ListNode dummy = new ListNode(Integer.MIN_VALUE), prev = dummy;\n while (head != null && head.next != null) {\n prev.next = head; // prev connects next 0 node.\n head = head.next; // head forward to a non-zero node.\n while (head != null && head.val != 0) { // traverse all non-zero nodes between two zero nodes.\n prev.next.val += head.val; // add current value to the previous zero node.\n head = head.next; // forward one step.\n }\n prev = prev.next; // prev point to the summation node (initially 0).\n }\n prev.next = null; // cut off last 0 node.\n return dummy.next;\n }\n```\n```python\n def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n dummy = prev = ListNode(-math.inf)\n while head and head.next:\n prev.next = head\n head = head.next\n while head and head.val != 0:\n prev.next.val += head.val\n head = head.next\n prev = prev.next\n prev.next = None \n return dummy.next\n```\n\n**Analysis:**\n\nTime: `O(n)`, extra space: `O(1)`, where `n` is the number of nodes.
107,907
Merge Nodes in Between Zeros
merge-nodes-in-between-zeros
You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0. For every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's. Return the head of the modified linked list.
Linked List,Simulation
Medium
How can you use two pointers to modify the original list into the new list? Have a pointer traverse the entire linked list, while another pointer looks at a node that is currently being modified. Keep on summing the values of the nodes between the traversal pointer and the modifying pointer until the former comes across a ‘0’. In that case, the modifying pointer is incremented to modify the next node. Do not forget to have the next pointer of the final node of the modified list point to null.
371
8
# Code\n```\nclass Solution {\npublic:\n ListNode* mergeNodes(ListNode* head) {\n ListNode *temp = head, *temp2 = head->next;\n int sum = 0;\n while(temp2){\n if(temp2->val == 0){\n temp->next = new ListNode(sum);\n temp->next->next = temp2->next;\n temp = temp->next; \n sum = 0; \n }\n sum+= temp2->val;\n temp2 = temp2->next;\n }\n return head->next;\n }\n};\n```
107,908
Construct String With Repeat Limit
construct-string-with-repeat-limit
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 repeatLimitedString possible. A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.
String,Greedy,Heap (Priority Queue),Counting
Medium
Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character.
4,845
91
We want to form a lexicographically largest string using the characters in a given string.\nBut we have to make sure that a letter is not repeated more than the given limit in a row (i.e consecutively).\n\nSo we use a ***priority_queue*** to pop the element which has the highest priority. *If it\'s count is less than the repeatLimit,* we directly add to the ans.\n\n*But if it\'s count is greater than the repeatLimit*, we just add the repeatLimit amount of the present character and we pop out the next priority character and add a single letter to the ans.\nThis makes that a letter is not repeated more than limit in a row and lexicographically largest is maintained. After adding to the ans, if we have extra characters left out, we just push back into priority_queue for the next use.\n\nHere *if we are not able to pop*, the next priority character, we just return the ans so as we cannot add more than repeatedLimit charecters in a row.\n```\nclass Solution {\npublic:\n string repeatLimitedString(string s, int k) { // k is the repeatLimit\n int n = s.length();\n unordered_map<char,int> m;\n for(int i=0;i<n;i++) m[s[i]]++;\n priority_queue<pair<char,int>> pq;\n for(auto i: m){\n pq.push({i.first,i.second}); // pushing the characters with their frequencies.\n }\n \n string ans = "";\n while(!pq.empty()){\n char c1 = pq.top().first;\n int n1 = pq.top().second;\n pq.pop();\n \n int len = min(k,n1); // Adding characters upto minimum of repeatLimit and present character count.\n for(int i=0;i<len;i++){ // adding the highest priority element to the ans.\n ans += c1;\n }\n \n char c2;\n int n2=0;\n if(n1-len>0){ // If the cnt of present character is more than the limit.\n if(!pq.empty()){ //Getting the next priority character.\n c2 = pq.top().first;\n n2 = pq.top().second;\n pq.pop();\n }\n else{\n return ans; // if there is no another letter to add, we just return ans.\n }\n ans += c2; // Adding next priority character to ans.\n \n // If the elements are left out, pushing them back into priority queue for next use.\n pq.push({c1,n1-len});\n if(n2-1>0) pq.push({c2,n2-1}); \n }\n }\n return ans;\n }\n};\n```\n**Upvote if it helps!**
107,912
Construct String With Repeat Limit
construct-string-with-repeat-limit
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 repeatLimitedString possible. A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.
String,Greedy,Heap (Priority Queue),Counting
Medium
Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character.
3,888
50
See my latest update in repo [LeetCode]()\n\n\n## Solution 1. Greedy + Counting\n\nStore frequency of characters in `int cnt[26]`.\n\nWe pick characters in batches. In each batch, we pick the first character from `z` to `a` whose `cnt` is positive with the following caveats:\n1. If the current character is the same as the one used in the previous batch, we need to skip it.\n2. On top of case 1, if the `cnt` of the character used in the previous batch is positive, then we can only fill a single character in this batch.\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n string repeatLimitedString(string s, int limit) {\n int cnt[26] = {};\n string ans;\n for (char c : s) cnt[c - \'a\']++;\n while (true) {\n int i = 25;\n bool onlyOne = false;\n for (; i >= 0; --i) {\n if (ans.size() && i == ans.back() - \'a\' && cnt[i]) { // the character of our last batch still has some count left, so we only insert a single character in this batch\n onlyOne = true;\n continue;\n }\n if (cnt[i]) break; // found a character with positive count, fill with this character\n }\n if (i == -1) break; // no more characters to fill, break;\n int fill = onlyOne ? 1 : min(cnt[i], limit);\n cnt[i] -= fill;\n while (fill--) ans += \'a\' + i;\n }\n return ans;\n }\n};\n```
107,913
Construct String With Repeat Limit
construct-string-with-repeat-limit
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 repeatLimitedString possible. A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.
String,Greedy,Heap (Priority Queue),Counting
Medium
Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character.
3,614
51
At first on looking into this problem it looked little complex,\n\nBut after thinking for some time, I am able to unwire it little easily..\n\nHere is the approach I took.\n\nIn-order to get a lexicographically larger number we know that it should have all larger alphabets in the starting of string like zzzzzzyyyyyyxxxxx.\n\nBut here they have given repeat count limit, so first things first we can sort the given string of characters using PriorityQueue.\n\n`1. Sort the given string in lexicographically large order using Max heap\n\nThen to maintain the repeat count and the lesser lexicographically small character once and then come back to larger charecter, I took the help of stack.\n\n 2. If the count of repeated character is more than the given repeat limit then add to stack\n 3. Then add the small character once and check whether the stack is empty\n 4. If its empty then you can continue in the same pattern\n 5. If stack is not empty then add the characters to its repeat count and again go for lesser character and repeat this process till the Priority Queue is empty.\n\nNow its time to look into the code :)\n\n\n```\n public String repeatLimitedString(String s, int repeatLimit) {\n PriorityQueue<Character> pq = new PriorityQueue<Character>((a,b)->b-a);\n for(char ch:s.toCharArray()){\n \tpq.add(ch);\n }\n StringBuffer res = new StringBuffer();\n ArrayList<Character> list = new ArrayList<Character>();\n Stack<Character> stk = new Stack<Character>();\n int count = 0;\n char previouschar = pq.peek();\n while(!pq.isEmpty()){\n \tchar curr = pq.poll();\n \tif(curr==previouschar){\n \t\tif(count<repeatLimit){\n \t\t\tres.append(curr);\n \t\t}\n \t\telse{\n \t\t\tstk.add(curr);\n \t\t}\n \t\tcount++;\n \t}\n \telse{\n \t\tif(stk.isEmpty()){\n \t\t\tcount=0;\n \t\t\tres.append(curr);\n \t\t\tpreviouschar = curr;\n \t\t\tcount++;\n \t\t}\n \t\telse{\n \t\t\tres.append(curr);\n \t\t\tcount=0;\n \t\t\twhile(!stk.isEmpty() && count<repeatLimit){\n \t\t\t\tres.append(stk.pop());\n \t\t\t\tcount++;\n \t\t\t}\n \t\t}\n \t}\n }\n return res.toString();\n }\n\n\nHappy learning.. upvote if its helpful\n\n
107,914
Construct String With Repeat Limit
construct-string-with-repeat-limit
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 repeatLimitedString possible. A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.
String,Greedy,Heap (Priority Queue),Counting
Medium
Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character.
1,048
11
We store the frequency of each character of the string in an array(A[26]). Now we start from the last index of the array which will store z as we need to generate output in lexiographically increasing order.\n\n```\n def repeatLimitedString(self, s: str, repeatLimit: int) -> str:\n arr = [0] * 26\n a = ord(\'a\')\n \n for char in s:\n arr[ord(char)-a] += 1\n\t\t\t\n # Using an array to store the answer as appending to a string is a costly operation\n ans = []\n curr = 25\n prev = 24 \n\t\t\n # We are starting with curr = 25 as we need to add the largest character first\n while curr >= 0:\n if arr[curr] == 0:\n curr -= 1\n continue\n \n\t\t\t# If the character is present in the string then we add it to our answer \n for i in range(min(repeatLimit, arr[curr])):\n ans.append(chr(curr + a))\n arr[curr] -= 1\n \n\t\t\t# If the above for loop was able to add all the characters then we can move on to the next one\n if arr[curr] == 0:\n curr -= 1\n continue\n \n\t\t\t# If the above for loop was not able to add all the characters then we need to add a second largest character before we can continue adding the largest character to our answer again\n g = False\n for j in range(min(prev, curr-1), -1, -1):\n if arr[j]:\n g = True\n arr[j] -= 1\n prev = j\n ans.append(chr(j+a))\n break\n\t\t\t# If g is false then we know that there were no other characters present other than the largest character\n if not g: break\n \n return \'\'.join(ans)\n```
107,916
Construct String With Repeat Limit
construct-string-with-repeat-limit
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 repeatLimitedString possible. A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.
String,Greedy,Heap (Priority Queue),Counting
Medium
Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character.
1,925
29
Please pull this [commit]() for solutions of weekly 281. \n\n```\nclass Solution:\n def repeatLimitedString(self, s: str, repeatLimit: int) -> str:\n pq = [(-ord(k), v) for k, v in Counter(s).items()] \n heapify(pq)\n ans = []\n while pq: \n k, v = heappop(pq)\n if ans and ans[-1] == k: \n if not pq: break \n kk, vv = heappop(pq)\n ans.append(kk)\n if vv-1: heappush(pq, (kk, vv-1))\n heappush(pq, (k, v))\n else: \n m = min(v, repeatLimit)\n ans.extend([k]*m)\n if v-m: heappush(pq, (k, v-m))\n return "".join(chr(-x) for x in ans)\n```
107,917
Construct String With Repeat Limit
construct-string-with-repeat-limit
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 repeatLimitedString possible. A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.
String,Greedy,Heap (Priority Queue),Counting
Medium
Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character.
750
9
As we **need lexicographically largest string** so start **adding largest character available**.\nOne thing we need to **take care of** is we **cannot repeat a character more than repeatLimit times** so **when this happens** **add 1 next greatest charcter.**\n```\nclass Solution {\npublic:\n string repeatLimitedString(string s, int repeatLimit) {\n \n int n(size(s));\n vector <int> m(26, 0);\n for (auto ch : s) m[ch-\'a\']++;\n \n priority_queue <pair<char, int>> pq;\n for (int i=0; i<26; i++)\n if (m[i]) \n pq.push({i+\'a\', m[i]});\n \n string res;\n \n while (!pq.empty()) {\n\t\t\n auto top = pq.top(); pq.pop(); // top contains lexicographically greatest character\n here :\n int lim = min(top.second, repeatLimit); // lim is number of times top can be added\n top.second -= lim;\n\t\t\t\n while (lim--) res.push_back(top.first);\n if (top.second > 0) {\n if (pq.empty()) return res; // if we dont get next greatest character then we cannot use remaining characters so return res\n auto next = pq.top(); pq.pop(); // next contains lexicographically greatest character smaller than top\n res.push_back(next.first);\n next.second -= 1;\n if (next.second) pq.push(next);\n goto here;\n }\n }\n \n return res;\n }\n};\n```\n\n**Upvote if it helps :)**
107,918
Construct String With Repeat Limit
construct-string-with-repeat-limit
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 repeatLimitedString possible. A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.
String,Greedy,Heap (Priority Queue),Counting
Medium
Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character.
2,178
19
1. Count all characters in 26 buckets (\'a\' to \'z\'). \n2. While we have characters left:\n\t- Find the largest bucket `i` that still has characters.\n\t- Take up to limit characters from bucket `i`.\n\t- Find the second largest bucket `j` that has characters.\n\t- Pick 1 character from bucket `j`.\n\nCaveats:\n- The largest bucket `i` could be the same as the second largest one `j` from the previous iteration.\n\t- So we should pick one less character from there.\n- Make sure `i` and `j` only go one direction (down) for the performance.\n\n**C++**\n```cpp\nstring repeatLimitedString(string s, int lim) {\n string res;\n int cnt[26] = {};\n for (auto ch : s)\n ++cnt[ch - \'a\'];\n for (int i = 25, j = 26; j >= 0; ) {\n while (i >= 0 && cnt[i] == 0)\n --i;\n if (i >= 0) {\n res += string(min(lim - (i == j), cnt[i]), \'a\' + i);\n cnt[i] -= min(lim - (i == j), cnt[i]);\n }\n j = min(i - 1, j);\n while (j >= 0 && cnt[j] == 0)\n --j; \n if (j >=0) {\n res += string(1, \'a\' + j);\n --cnt[j];\n }\n }\n return res;\n}\n```
107,919
Construct String With Repeat Limit
construct-string-with-repeat-limit
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 repeatLimitedString possible. A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.
String,Greedy,Heap (Priority Queue),Counting
Medium
Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character.
446
9
\n \n \n The idea is simple, keep a max heap of all the characters and their available counts.\n If the max character element at the top of the heap is already exceeding the limit interms of count,\n then pop the next one and add to heap. Also add back the unused max character element to the heap.\n \n \n```\ndef repeatLimitedString(self, s: str, limit: int) -> str:\n\theap = [ (-ord(ch), ch, count) for ch, count in Counter(s).items() ]\n\theapify(heap)\n\tres, count = [], 0\n\n\twhile heap:\n\t\tmax_heap_key, ch, rem = heappop(heap)\n\t\tif res and res[-1] == ch and (count+1) > limit:\n\t\t\tif not heap: break\n\t\t\tmax_heap_key2, ch2, rem2 = heappop(heap)\n\t\t\theappush(heap, (max_heap_key, ch, rem))\n\t\t\tmax_heap_key, ch, rem = max_heap_key2, ch2, rem2\n\n\t\tif res and res[-1] != ch:\n\t\t\tcount = 0\n\n\t\tres.append(ch)\n\t\trem -= 1\n\t\tif rem:\n\t\t\theappush(heap, (max_heap_key, ch, rem))\n\t\tcount += 1\n\treturn \'\'.join(res) \n```\n```\n\t
107,922
Construct String With Repeat Limit
construct-string-with-repeat-limit
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 repeatLimitedString possible. A string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.
String,Greedy,Heap (Priority Queue),Counting
Medium
Start constructing the string in descending order of characters. When repeatLimit is reached, pick the next largest character.
687
6
My easy-understanding solution, O(n) time complexity and O(26) -> O(1) space.\n```\nclass Solution {\n public String repeatLimitedString(String s, int repeatLimit) {\n int[] counter = new int[26];\n int max = 0;\n for (char ch : s.toCharArray()) {\n int curr = ch - \'a\';\n max = Math.max(max, curr);\n counter[curr]++;\n }\n int repeated = 0;\n StringBuilder builder = new StringBuilder();\n while (max >= 0) {\n builder.append((char)(\'a\' + max));\n counter[max]--;\n repeated++;\n if (counter[max] == 0) {\n max = findNextMax(counter, max - 1);\n repeated = 0;\n\t\t\t\tcontinue;\n } \n if (repeated == repeatLimit) {\n\t\t\t\t// Greedy, use the next possible char once and get back to curr.\n\t\t\t\t// if no other char available, the curr word is the largest subsequence. \n int lower = findNextMax(counter, max - 1);\n if (lower < 0) {\n return builder.toString();\n }\n builder.append((char)(\'a\' + lower));\n counter[lower]--;\n repeated = 0;\n }\n }\n return builder.toString();\n }\n \n private int findNextMax(int[] counter, int from) {\n int curr = from;\n while (curr >= 0) {\n if (counter[curr] > 0) {\n return curr;\n }\n curr--;\n }\n return curr;\n }\n}\n```
107,940
Count Array Pairs Divisible by K
count-array-pairs-divisible-by-k
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that:
Array,Math,Number Theory
Hard
For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k? The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers present in the array efficiently.
6,624
154
## Intuition\nLet\'s first understand this property:\n\n<b>If (a*b)%k==0, then\ngcd(a,k) * gcd(b,k) % k is also 0</b>\n\nLet\u2019s assume two numbers 504 and 819. Their prime factorization can be written as:\n\n504 = (2^3) * (3^2) * 7\n819 = (3^2) * 7 * 13\n\nNow gcd(504,819) = 63 and 63 = (3^2) * 7\n\n<b>gcd(a,b) is the multiplication of common prime factors of a and b.</b>\n\nComing back to the statement\nHow gcd(a,k) * gcd(b,k) % k is 0 ?\n\nFor any number to be divisble by k it need to have atleast all the prime factors of k.\n\ngcd(a,k) = Multiplication of all prime factors of k available in a.\nand\ngcd(b,k) = Multiplication of all prime factors of k available in b.\n\nIf gcd(a,k) * gcd(b,k) % k is 0, it means some of the prime factors of k are contributed by a and some of the prime factors of k are contributed by b and thier multiplication has all the prime factors of k which means a*b is divisble by k.\n\nWe dont care about prime factors of a or b which are not prime factors of k because they will not help us in making a*b divisible by k.\n\nExample:\n\nLet k=84, a=24, b=273\n\nk = 84 = (2^2) * 3 * 7\na = 24 = (2^3) * 3\nb = 273 = 3 * 7 * 13\n\ngcd(a,k) = (2^2) * 3 (Common prime factors of a and k)\ngcd(b,k) = 7 * 3 (Common prime factors of b and k)\n\ngcd(a,k) * gcd(b,k) = (2^2) * (3^2) * 7\nwhich has all prime factors of k thus a*b is divisble by k.\n\n## Now the solution:\n\nAs compared to checking for every pair, if we check for gcd of every number with k then the operations will be less because the number of prime factors of a number will be less.\n\nCode:\n```\ntypedef long long ll;\n\nclass Solution {\npublic:\n long long countPairs(vector<int>& nums, int k) {\n unordered_map<ll, ll> gcdCount;\n ll ans = 0;\n for (ll i = 0; i < nums.size(); ++i)\n {\n ll currgcd = __gcd(nums[i], k);\n for (auto &[gc_d, count] : gcdCount)\n if ((currgcd * gc_d) % k == 0)\n ans += count;\n gcdCount[currgcd]++;\n }\n return ans;\n }\n};\n```\n\n## Time Complexity - O(N*sqrt(K))\n\nWhy sqrt(K):\nSince we are taking gcd, it means we are considering factors of K and the number of factors of K will not be above 2*sqrt(K).\n\nI hope you got the logic.\n\nYou can ask your questions in comment section.\n\nPlease upvote if you found this helpful.
107,960
Count Array Pairs Divisible by K
count-array-pairs-divisible-by-k
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that:
Array,Math,Number Theory
Hard
For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k? The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers present in the array efficiently.
5,668
57
* Firstly, generate all divisors of k.\n* Secondly, for each index `i` in `nums`, count the number of index `j` hold: \n * `j < i`\n\t* `nums[j] MOD k/GCD(k, nums[i]) == 0`\n* Obviously, `k/GCD(k, nums[i])` is a divisor of k. Therefore, we just need a counter to maintain the number of elements on the left divisible for each divisor of k.\n* Complexity: \n\t* Time: O(N * sqrt(K))\n\t* Space: O(sqrt(K))\n\n```\nclass Solution:\n def coutPairs(self, nums: List[int], k: int) -> int:\n N, output = len(nums), 0\n divisors = []\n counter = Counter()\n \n for i in range(1, k + 1):\n if k % i == 0:\n divisors.append(i)\n \n for i in range(0, N):\n remainder = k // math.gcd(k, nums[i])\n output += counter[remainder]\n for divisor in divisors:\n if nums[i] % divisor == 0:\n counter[divisor] += 1\n \n return output\n```
107,962
Count Array Pairs Divisible by K
count-array-pairs-divisible-by-k
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that:
Array,Math,Number Theory
Hard
For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k? The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers present in the array efficiently.
3,981
43
For a given number, only the gcd between current number `num[i]` and k need to be considered. All we need to do is to count/group the numbers by the gcds. And if `gcd(num[i], k) * gcd(num[j], k)` is divisible by k , `num[i] * num[j]` should also be divisible.\n\n```\nclass Solution {\n public long coutPairs(int[] nums, int k) {\n long result = 0;\n Map<Integer, Integer> gcdMap = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int gcd = findGcd(nums[i], k);\n for (int num : gcdMap.keySet()) {\n if ((long) gcd * num % k == 0) { // Need to convert gcd(i) * gcd(j) to long, sad java\n result += gcdMap.get(num);\n }\n }\n gcdMap.put(gcd, gcdMap.getOrDefault(gcd, 0) + 1);\n }\n return result;\n }\n private int findGcd(int x, int y) {\n if (x < y) {\n return findGcd(y, x);\n }\n return y == 0 ? x : findGcd(y, x % y);\n }\n}\n```
107,963
Count Array Pairs Divisible by K
count-array-pairs-divisible-by-k
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that:
Array,Math,Number Theory
Hard
For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k? The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers present in the array efficiently.
9,285
47
# **Explanation**\nCount all elements greatest common divisor with `k`.\nFor each pair `(a, b)` of divisors, check if `a * b % k == 0`\n<br>\n\n# **Complexity**\nTime `O(nlog100000 + k * k)`\nSpace `O(k)`\nwhere `k` is the number of divisors of `k`.\n\n# **Value of K**\nprovided by @megurine\n83160 and 98280 have the biggest number of diviors, which is 128.\n83160 = 11*7*5*3*3*3*2*2*2\n98280 = 13*7*5*3*3*3*2*2*2\n\nprovided by @endlesscheng\nMaximal number of divisors of any n-digit number\n\n<br>\n\n**Java**\nby @blackspinner\n```java\n public long countPairs(int[] nums, int k) {\n Map<Long, Long> cnt = new HashMap<>();\n long res = 0L;\n for (int x : nums) {\n cnt.merge(BigInteger.valueOf(x).gcd(BigInteger.valueOf(k)).longValue(), 1L, Long::sum);\n }\n for (long x : cnt.keySet()) {\n for (long y : cnt.keySet()) {\n if (x <= y && x * y % k == 0L) {\n res += x < y ? cnt.get(x) * cnt.get(y) : cnt.get(x) * (cnt.get(x) - 1L) / 2L;\n }\n }\n }\n return res;\n }\n```\n**C++**\nby @alexunxus\n```\nlong long coutPairs(vector<int>& nums, int k) {\n unordered_map<int, int> mp;\n for (int& nu: nums) {\n mp[gcd(nu, k)]++;\n }\n long long res = 0;\n for (auto& [a, c1]: mp) {\n for (auto & [b, c2]: mp) {\n if (a <= b && a*(long) b %k == 0) {\n res += a < b?(long)c1*c2:(long)c1*(c1-1)/2;\n }\n }\n }\n return res; \n }\n```\n**Python**\n```py\n def coutPairs(self, A, k):\n cnt = Counter(math.gcd(a, k) for a in A)\n res = 0\n for a in cnt:\n for b in cnt:\n if a <= b and a * b % k == 0:\n res += cnt[a] * cnt[b] if a < b else cnt[a] * (cnt[a] - 1) // 2\n return res\n```\n
107,964
Count Array Pairs Divisible by K
count-array-pairs-divisible-by-k
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that:
Array,Math,Number Theory
Hard
For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k? The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers present in the array efficiently.
3,261
22
I tried writing more detailed comments below, hope it helps!\n```\nclass Solution {\npublic:\n long long coutPairs(vector<int>& nums, int k) {\n unordered_map<int,int> factorCount;\n long long result =0;\n int previousIndexCount = 0; // stores any Index that was traversed before\n for (int i=0;i<nums.size(); i++){\n int factor = gcd(nums[i], k); // this is the "useful" part of nums[i]\n int missingFactor = k/factor; // what other factor is needed to form k\n \n if (missingFactor==1){ // if missingFactor is 1, the that means nums[i] can match with any previous index to form a pair, k*n %k == 0\n result += previousIndexCount;\n }else{ // if m is not 1, we can check if any previous index has the missing factor\n for (auto it=factorCount.begin(); it!=factorCount.end(); it++){\n if ( it->first % missingFactor == 0){\n result += it->second;\n }\n }\n }\n // only add the "useful" factor part to the map\n factorCount[factor]++;\n previousIndexCount++;\n \n }\n return result;\n }\n};\n```
107,965
Count Array Pairs Divisible by K
count-array-pairs-divisible-by-k
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that:
Array,Math,Number Theory
Hard
For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k? The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers present in the array efficiently.
1,990
7
```\nclass Solution {\npublic:\n int mx = 1e5 + 5;\n void update(vector<long long>& divisors, int num) {\n\t\t//update divisors of num\n for(int i = 1; i * i <= num; i++) {\n if(num % i == 0) {\n if(i == num / i) divisors[i]++;\n else {\n divisors[i]++;\n divisors[num/i]++;\n }\n }\n }\n }\n long long coutPairs(vector<int>& nums, int k) {\n vector<long long> divisors(mx, 0LL);\n long long res = 0LL;\n for(int i = 0; i < nums.size(); i++) {\n\t\t\t//number to be multiplied with num[i] to make it divisible by k\n int r = k / (__gcd(nums[i], k));\n\t\t\t\n\t\t\t//numbers with divisors r\n res += (long long)divisors[r];\n\t\t\t\n\t\t\t//update the divisors of num[i]\n update(divisors, nums[i]);\n }\n return res;\n }\n};\n```
107,967
Count Array Pairs Divisible by K
count-array-pairs-divisible-by-k
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that:
Array,Math,Number Theory
Hard
For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k? The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers present in the array efficiently.
1,660
6
Please pull this [commit]() 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: factors.append(x)\n ans = 0 \n freq = Counter()\n for x in nums: \n x = gcd(x, k)\n ans += freq[k//x]\n for f in factors: \n if x % f == 0 and f <= x//f: \n freq[f] += 1\n if f < x//f: freq[x//f] += 1\n return ans \n```
107,968
Count Array Pairs Divisible by K
count-array-pairs-divisible-by-k
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that:
Array,Math,Number Theory
Hard
For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k? The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers present in the array efficiently.
1,439
9
#### Based on [this solution]((Nsqrt(K))-Easy-understand-solution) here is a line by line detial explanations\n---\n\n##### nums = [2,3,4,6,8], k = 4\n\n```\nclass Solution:\n def coutPairs(self, nums: List[int], k: int) -> int:\n N, output = len(nums), 0\n divisors = []\n counter = Counter()\n \n for i in range(1, k + 1):\n if k % i == 0:\n divisors.append(i)\n```\n**For each number, there is the smallest value to multiply that makes it divisible by \'k\'**\nex: 6 should be multiplied by at least 2 to be divisible by 4\n\t&nbsp;&nbsp;&nbsp;&nbsp; 4 should be multiplied by at least 1 to be divisible by 4\n\t&nbsp;&nbsp;&nbsp;&nbsp; 3 should be multiplied by at least 4 to be divisible by 4\n\t\n**Divisors collects all the posiibility of those smallest numbers**\n > divisor = [1,2,4]\n \n\n```\n for i in range(0, N):\n remainder = k // math.gcd(k, nums[i])\n\t\t\toutput += counter[remainder]\n```\n**remainder calculate how much num[i] should at least be multiplied to be divisible by \'k\'**\nEx: num[i] = 6 -> reminder = 4 // gcd(4,6) = 2\n**"counter[remainder]" indicates how many numbers in \'nums\' are divisible by remainder(2)**\n```\n for divisor in divisors:\n if nums[i] % divisor == 0:\n counter[divisor] += 1\n \n return output\n```\n**Then define which group num[i] belongs to**\nEx: nums[i] = 6, then nums[i] is divisible by 1, 2\n\t&nbsp;&nbsp;&nbsp;&nbsp; whick mean if the remainder of nums[n] is 1 or 2 it can pair with \'6\' \n
107,969
Count Array Pairs Divisible by K
count-array-pairs-divisible-by-k
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that:
Array,Math,Number Theory
Hard
For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k? The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers present in the array efficiently.
581
6
```\nDO UPVOTE PLS ;))\n\n\nclass Solution {\npublic:\n long long countPairs(vector<int>& nums, int k) {\n unordered_map<int,int>m;\n long long ans=0;\n for(int i=0;i<nums.size();i++)\n {\n int gcd=__gcd(nums[i],k);\n int needed_num=k/gcd; // gcd(a,k) *gcd(b,k)%k==0 is same as a*b%k==0\n for(auto x:m)\n {\n if(x.first%needed_num==0)\n ans+=x.second;\n }\n m[gcd]++;\n }\n return ans;\n }\n};\n```
107,973
Count Array Pairs Divisible by K
count-array-pairs-divisible-by-k
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that:
Array,Math,Number Theory
Hard
For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k? The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers present in the array efficiently.
2,546
11
**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 10 so by far we have found 12 so the [gcd]() of 12,10 will be 2 now what is the other counter we need to find it is 5 hence if we find 5\'s multiple or 5 we will add this pair to answer**\n`So the time complexity here won\'t be O(n^2) because a number can only have limited factors hence for 10^5 the max will be (10^5)^1/2 so at max the loop will iterate upto 100 - 200 (roughly) `\n```py\nclass Solution:\n def countPairs(self, nums: List[int], k: int) -> int:\n counter = Counter() #hashmap dicitionary of python\n ans = 0\n n = len(nums)\n \n for i in range(n):\n x = math.gcd(k,nums[i]) #ex: 10 = k and we have nums[i] as 12 so gcd will be 2\n want = k // x #what do we want from upper ex: we need 5\n for num in counter:\n if num % want == 0: #so if we find a number that is divisible by 5 then we can multiply it to 12 and make it a factor of 10 for ex we find 20 so it will be 240 which is divisible by 10 hence we will add it to answer\n ans += counter[num] #we are adding the freq as we can find no of numbers that have same factor\n counter[x] += 1 #here we are increasing the freq of 2 so that if we find 5 next time we can add these to the answer\n return ans\n```\n```java\npublic class Solution {\n public int countPairs(int[] nums, int k) {\n // Create a HashMap to count the occurrences of numbers\n Map<Integer, Integer> counter = new HashMap<>();\n int ans = 0;\n int n = nums.length;\n\n for (int i = 0; i < n; i++) {\n int gcdResult = gcd(k, nums[i]); // Calculate the GCD of \'k\' and \'nums[i]\'\n int desiredFactor = k / gcdResult; // Calculate the desired factor to form a pair with \'nums[i]\'\n\n for (int num : counter.keySet()) {\n if (num % desiredFactor == 0) {\n // If \'num\' is divisible by the desired factor, it can form pairs with \'nums[i]\'\n // Add the frequency of \'num\' to the answer\n ans += counter.get(num);\n }\n }\n\n // Increase the count of \'gcdResult\' in the HashMap\n counter.put(gcdResult, counter.getOrDefault(gcdResult, 0) + 1);\n }\n\n return ans;\n }\n```\n
107,974
Count Array Pairs Divisible by K
count-array-pairs-divisible-by-k
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that:
Array,Math,Number Theory
Hard
For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k? The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers present in the array efficiently.
1,881
9
We know that a number n is divisible by a number m if ,\n GCD(n,m) =m\n\nsimilarly (nums[i] * nums[j]) is divisible by k if their GCD is k .\nknowing this if we just precalculate count of how many numbers are divisible by a number num( say) (for all num 1 to 10^5)\n\nthen we just need to loop for each element of array and finding out the remaing number( remaining_factor) needed to be multiplied to it so as to make the GCD equals to k.\nthen for this number the count of pairs will be as much as the multiple of remaining_factor present in array (ignoring the number itself)\n\nThus adding count of pairs for each i in nums we will get our answer . we will have to divide the final answer by 2 as we have counted each pair twice for any pair (i , j) .\n\nTime - O(n * log(n) ) // both finding the multiples for all i [0,n] and taking gcd for each element with k takes nlogn time . so worst case time complexity is (nlogn) \n\nSpace - O(n) // we need two arrays of size n .\n\n```\nclass Solution {\npublic:\n int count[100001];\n int count_of_multiples[100001];\n \n long long coutPairs(vector<int>& nums, int k) {\n int n=nums.size();\n\n for(int i=0;i<n;i++) count[nums[i]]++; // counting frequency of elements\n \n for(int i=1;i<100001;i++){\n for(int j=i;j<100001;j=j+i) count_of_multiples[i]+=count[j]; //counting total elements present in array which are multiple of i\n }\n \n long long ans=0;\n for(int i=0;i<n;i++){\n long long factor=__gcd(k,nums[i]);\n long long remaining_factor= ( k / factor);\n long long j = count_of_multiples[remaining_factor];\n if(nums[i]%remaining_factor==0)j--; // if nums[i] itself is multiple of remaining factor then we to ignore it as i!=j\n ans+=j;\n }\n \n ans/=2; // as we have counted any distinct pair (i,j) two times , we need to take them only once\n return ans;\n }\n};\n```
107,977
Count Array Pairs Divisible by K
count-array-pairs-divisible-by-k
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that:
Array,Math,Number Theory
Hard
For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k? The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers present in the array efficiently.
1,065
7
## Basic strategy\n* We process the numbers one by one traversing from left to right.\n* At any index `j`, we\'re looking for all indices `i` (`i < j`) such that `nums[i] * nums[j] = 0 (mod k)`.\n Let\'s write it as `x * a = 0 (mod k)` substituting `a` for `nums[j]` and `x` for (a possible) `nums[i]` for readability.\n We\'re looking for (count of) all `x`s that satisfy the above and which we\'ve **already encountered before** in our traversal.\n\n## Some maths now\n* What are the solutions for the linear recurrence `a*x = b (mod k)` ?\nThere could be infinitely many solutions depending upon whether `gcd(a, k)` divides `b` or not.\nIn our case, `b` is `0`. So, there are infinitely many solutions.\n(But we\'re looking for only those that occur in our array before `a` in left to right traversal)\n* In general, when there are more than one solution, we express the set of all possible solutions as\n `x = x_0 + n * r (mod k)` where\n `x_0 = b / gcd(a, k)` \n `r = k / gcd(a, k)` -------------------------------------------------- **(1)**\n and `0 <= n < gcd(a, k)`\n* In our case, `x_0 = 0` so, the above simplifies to\n `x = n * r (mod k)` for `0 <= n < gcd(a, k)` ------------- **(2)**\n This can be written as\n `x = q*k + n*r` for some integer `q` ------------------------------ **(3)**\n `x = q*r*gcd(a,k) + n*r` or\n `x = r*(q*gcd(a,k) + n)` ------------------------------------------ **(4)**\n* From the above, we can see that `r` is a divisor of `k` (from (1)) and also that `r` is a divisor of `x`.\n In fact, (3) tells us that any number divisible by `r` is a solution to our equation.\n Why?\n Well, let `x` be divisible by `r`. So we can write\n `x = r * Q` for some integer `Q`\n By Euclid\'s division lemma, any integer `Q` can be writen as\n `Q = p*quot + rem` for any positive `p` such that `0 <= rem < p`.\n If we use `gcd(a, k)` for `p`, we get\n `x = r * Q = r * (gcd(a,k)*qout + rem)` where `0 <= rem < gcd(a,k)`\n This is exactly the form of (4).\n\n## Back to the main problem\nCool, coming back to our problem, and armed with the maths we did before, we can calculate\n`r = k / gcd(nums[j], k)`\nand then count all `nums[i]` that we\'ve seen before which are divisibly by `r`.\n\nSo, we\'d need to determine all divisors of `k` and the keep track of the count of all numbers we\'ve\nseen before in our traversal that are divisible by each of these divisors\nWe can keep these counts updated as we traverse.\n\n## Complexity\n* Time: For each number, we go over all divisors of `k`. A tight bound on the number of divisors can be had, but `sqrt(k)` is a good upper bound (since divisors occur in pairs). So time complexity is `O(n * sqrt(k))`. This could be considered amortized cost as the amortized `O(1)` cost of unordered_map access is should also be in there.\n* Space: `sqrt(k)` each for the divisors vector and the the unordered_map. So `O(sqrt(k))` in total.\n```\nclass Solution {\npublic:\n long long coutPairs(vector<int>& nums, int k) {\n using sum_type = long long;\n \n // divisor -> count of nums seen so far divisible by divisor\n unordered_map<int,int> nums_divisible_by_divisor;\n vector<int> divisors;\n \n // Populate the divisors of `k`\n for(int i = 1; i <= k; i++) {\n if(k % i == 0)\n divisors.push_back(i);\n }\n \n sum_type total = 0;\n \n for(auto const &num: nums) {\n // Refer to the text outside of code, to get the significance of `r`\n int r = k / gcd(num, k);\n \n // We do this to avoid adding elements in the hashmap while doing lookup.\n // That might be convenient syntax wise, but we could end up adding\n // quite a few useless values in the hashmap. It would not lead to\n // incorrect results, but might trigger some rebalancing which is unnecessary.\n if(auto it = nums_divisible_by_divisor.find(r); it != nums_divisible_by_divisor.end())\n total += it->second;\n \n // This is where we update the divisor -> counts map for the incoming number `num`\n // and maintain the "seen so far" invariant.\n for(auto const &divisor : divisors) {\n if(num % divisor == 0)\n nums_divisible_by_divisor[divisor]++;\n }\n }\n \n return total;\n }\n};\n```
107,980
Count Array Pairs Divisible by K
count-array-pairs-divisible-by-k
Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that:
Array,Math,Number Theory
Hard
For any element in the array, what is the smallest number it should be multiplied with such that the product is divisible by k? The smallest number which should be multiplied with nums[i] so that the product is divisible by k is k / gcd(k, nums[i]). Now think about how you can store and update the count of such numbers present in the array efficiently.
147
5
For this problem, we wish to find all pairs of numbers `(a,b)` such that `a*b % k == 0`.\nIt\'s clear that doing this for all pairs is too expensive, so we need to somehow group \nnumbers together.\n\nFirst, some background.\n\nAll numbers have a prime factorization. For example, `192 = 2*2*2*7*7`. \nFor prime numbers, the factor is simply itself times 1.\n\nThe greatest common denominator of two numbers, i.e. `gcd(a,b)` is the common\nprime factorizations of a and b. For example, given `a = 192 = 2*2*2*7*7` and \n`b = 21 = 3*7`, the GCD is `7`.\n\nWhen we take the GCD (`a,k`) of each element `a` in `nums`, we remove all\nprime factors from each element that are not in common with `k`. We know \nthat there aren\'t that many of these factors - in fact, we can find all factors \nthat evenly divide k in `O(sqrt(N))` time, so there are *at most* sqrt(N) factors.\n\nLet\'s take an example from one of the test cases:\n\n```\nnums = [8, 10, 2, 5, 9, 6, 3, 8, 2]\nk = 6\n```\n\nNow, `k = 6 = 3*2`. The only possible factors that divide k are `6, 3, 2, 1`, so\nthere can be at most 4 different numbers after doing `gcd(a,k)`:\n\n```\nnums = [8, 10, 2, 5, 9, 6, 3, 8, 2]\nfactors = [2*2*2, 2*5, 2, 5, 3*3, 3*2, 3, 2*2*2, 2]\nk = 2*3\ncommon_factors = [2, 2, 2, 1, 3, 6, 3, 2, 2]\n```\n\nNotice how few factors there are.\n\nNow comes the interesting part: since `gcd(a,k)` captures common prime factors\nbetween `a` and `k`, then any `gcd(a,k) * gcd(b,k)` where `a` and `b` contain\nall factors in `k` must be evenly divisible by `k`. If a factor exists e.g.\ntwice, it will just create a larger number still divisible by `k`.\n\nTherefore, `gcd(a,k)*gcd(b,k) % k = 0` if `(a * b) % k = 0`.\n\nThe final tricky part is when `a` == `b`. This can happen when e.g. `k` is a square\nand `a` is its root, or when `a` is equal to `k`. \n\nFor this case, the number of unique pairs is `n(n-1)/2`: there are `n` elements to \nchoose from in the first element, then `n-1`, hence `n*(n-1)`. Then divide by \nhalf to removeduplicates.\n\n# Solution\n\n```go\nfunc countPairs(nums []int, k int) int64 {\n\tgcd := func(a, b int) int {\n\t\tfor b != 0 {\n\t\t\ta, b = b, a%b\n\t\t}\n\t\treturn a\n\t}\n \n\tn := int(math.Sqrt(float64(k)))\n\tgcds := make(map[int]int, n)\n\tfor _, num := range nums {\n\t\tgcds[gcd(num, k)]++\n\t}\n\n\tvar res int\n\tfor a, n1 := range gcds {\n\t\tfor b, n2 := range gcds {\n\t\t\tif a > b || (a*b)%k != 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif a != b {\n\t\t\t\tres += n1 * n2\n\t\t\t} else { // a == b\n\t\t\t\tres += n1 * (n1 - 1) / 2\n\t\t\t}\n\t\t}\n\t}\n\treturn int64(res)\n}\n```
107,985
Cells in a Range on an Excel Sheet
cells-in-a-range-on-an-excel-sheet
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
String
Easy
From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order.
347
6
<!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n<!-- # Approach -->\n<!-- Describe your approach to solving the problem. -->\n\n<!-- # Complexity\n- Time complexity: -->\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n<!-- - Space complexity: -->\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {string} s\n * @return {string[]}\n */\nfunction parser(s) {\n\tlet result = [];\n\tlet index = s.indexOf(\':\');\n\tresult.push(s[0]);\n\tresult.push(+s.slice(1, index));\n\tresult.push(s[index + 1]);\n\tresult.push(+s.slice(index + 2));\n\treturn result;\n}\n\nvar cellsInRange = function (s) {\n\tlet parserResult = parser(s);\n\tlet firstLetter = parserResult[0];\n\tlet firstNum = parserResult[1];\n\tlet secondLetter = parserResult[2];\n\tlet secondNum = parserResult[3];\n\tlet alphabet = \'abcdefghijklmnopqrstuvwxyz\'.toUpperCase();\n\tlet letters = alphabet.slice(alphabet.indexOf(firstLetter), alphabet.indexOf(secondLetter) + 1).split(\'\');\n\tlet result = [];\n\tletters.forEach(letter => {\n\t\tfor (let num = firstNum; num < secondNum + 1; num++) {\n\t\t\tresult.push(letter + num);\n\t\t}\n\t});\n\treturn result;\n};\n\n```
108,009
Cells in a Range on an Excel Sheet
cells-in-a-range-on-an-excel-sheet
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
String
Easy
From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order.
5,581
68
**Python**\n```python\nclass Solution:\n def cellsInRange(self, s: str) -> List[str]:\n return [chr(c) + chr(r) for c in range(ord(s[0]), ord(s[3]) + 1) for r in range(ord(s[1]), ord(s[4]) + 1)]\n```\n**C++**\n```cpp\nvector<string> cellsInRange(string s) {\n vector<string> res;\n for (char c = s[0]; c <= s[3]; ++c)\n for (char r = s[1]; r <= s[4]; ++r)\n res.push_back({c, r});\n return res;\n}\n```
108,015
Cells in a Range on an Excel Sheet
cells-in-a-range-on-an-excel-sheet
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
String
Easy
From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order.
5,191
43
\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 cells.add("" + c + r);\n }\n }\n return cells;\n }\n```\n```python\n def cellsInRange(self, s: str) -> List[str]:\n c1, c2 = ord(s[0]), ord(s[3])\n r1, r2 = int(s[1]), int(s[4])\n return [chr(c) + str(r) for c in range(c1, c2 + 1) for r in range(r1, r2 + 1)]\n```\nPython 3 Two liner: credit to **@stefan4trivia**:\n```python\ndef cellsInRange(self, s: str) -> List[str]:\n c1, r1, _, c2, r2 = map(ord, s)\n return [chr(c) + chr(r) for c in range(c1, c2 + 1) for r in range(r1, r2 + 1)]\n```\n**Analysis:**\n\nTime: `O((c2 - c1 + 1) * (r2 - r1 + 1))`, space: `O(1)` - excluding return space.
108,017
Cells in a Range on an Excel Sheet
cells-in-a-range-on-an-excel-sheet
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
String
Easy
From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order.
1,233
14
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n**cs= column Start**\n**ce= column End**\n**rs= row Start**\n**re= row End**\n\n**c= Column**\n**r= Row**\n\n# Code\n```\n\nclass Solution {\n public List<String> cellsInRange(String s) {\n\n // runtime 1 ms\n\n //cs= Column Start //ce= Column End\n //rs= Row Start //re= Row End\n char cs=s.charAt(0),ce=s.charAt(3);\n char rs=s.charAt(1),re=s.charAt(4);\n\n List<String> ls=new ArrayList<>();\n //c - cell\n for(char c=cs;c<=ce;c++){\n // r - row\n for(char r=rs;r<=re;r++){\n ls.add(new String(new char[]{c,r} ));\n }\n }\n\n return ls;\n\n\n \n }\n}\n```\n![478xve.jpg]()\n\n
108,019
Cells in a Range on an Excel Sheet
cells-in-a-range-on-an-excel-sheet
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
String
Easy
From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order.
646
5
```\nclass Solution {\npublic:\n vector<string> cellsInRange(string s) {\n vector<string>ans;\n char leftChar = s[0];\n char rightChar = s[3];\n \n while (leftChar <= rightChar){\n int low = s[1] - \'0\', high = s[4] - \'0\';\n while (low <= high){\n ans.push_back(leftChar + to_string(low));\n low++;\n }\n leftChar++;\n }\n return ans;\n }\n};\n```
108,020
Cells in a Range on an Excel Sheet
cells-in-a-range-on-an-excel-sheet
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
String
Easy
From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order.
2,448
23
```\nclass Solution {\npublic:\n vector<string> cellsInRange(string s) {\n \n vector<string>ans;\n \n for(char ch=s[0];ch<=s[3];ch++)\n {\n for(int i=s[1]-\'0\';i<=s[4]-\'0\';i++)\n {\n string res="";\n res+=ch;\n res+=to_string(i);\n ans.push_back(res);\n \n }\n }\n return ans;\n }\n};\n```\n\n**Pls upvote the solution if you found helpful, it means a lot.\nAlso comment down your doubts.\nHappy Coding : )**\n
108,027
Cells in a Range on an Excel Sheet
cells-in-a-range-on-an-excel-sheet
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
String
Easy
From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order.
793
5
```\nclass Solution:\n def cellsInRange(self, s: str) -> List[str]:\n c1,r1,c2,r2 = s[:1], s[1:2], s[3:4], s[4:]\n a=[]\n for i in range(ord(c1),ord(c2)+1):\n x=chr(i)\n for j in range(int(r1),int(r2)+1):\n y=x+str(j)\n a.append(y)\n return a\n```
108,033
Cells in a Range on an Excel Sheet
cells-in-a-range-on-an-excel-sheet
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
String
Easy
From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order.
1,310
18
The strategy for this problem is straightforward:\n- we traverse from start letter to end letter\n- for each letter, we traverse from start number to end number\n\nI can\'t find tricks for this problem, if you find some please comment, thanks.\n\nHere\'s the code I submitted during the contest:\n\n```js\nconst cellsInRange = (s) => {\n const [fromLetter, fromNum, , toLetter, toNum] = s;\n const ret = [];\n for (let l1 = fromLetter.charCodeAt(0), l2 = toLetter.charCodeAt(0); l1 <= l2; ++l1) {\n for (let n1 = +fromNum, n2 = +toNum; n1 <= n2; ++n1) {\n ret.push(String.fromCharCode(l1) + n1);\n }\n }\n return ret;\n};\n```
108,034
Cells in a Range on an Excel Sheet
cells-in-a-range-on-an-excel-sheet
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
String
Easy
From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order.
341
6
\n```C# []\npublic class Solution {\n public IList<string> CellsInRange(string s) {\n List<string> res=new List<string>();\n for (char c = s[0]; c <= s[3]; ++c)\n for (char r = s[1]; r <= s[4]; ++r)\n res.Add($"{c}{r}");\n return res;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<string> cellsInRange(string s) {\n vector<string> res;\n for (char c = s[0]; c <= s[3]; ++c)\n for (char r = s[1]; r <= s[4]; ++r)\n res.push_back({c, r});\n return res;\n } \n};\n```\n\n
108,037
Cells in a Range on an Excel Sheet
cells-in-a-range-on-an-excel-sheet
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
String
Easy
From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order.
1,385
9
```\nclass Solution:\n def cellsInRange(self, s: str) -> List[str]:\n result=[]\n for i in range(ord(s[0]),ord(s[3])+1):\n rs=""\n for j in range(int(s[1]),int(s[4])+1):\n rs=chr(i)+str(j)\n result.append(rs)\n return result\n\t
108,039
Cells in a Range on an Excel Sheet
cells-in-a-range-on-an-excel-sheet
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
String
Easy
From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order.
641
5
**Alogorithm**:\nWe have to iterate from `col1 to col2` **letters** and for every letter we just have to traverse from `row1 to row2` **number.**\nIn this way we will get our answer in **sorted order** automatically.\n\n**C++**\n \n\tvector<string> cellsInRange(string s){\n //result answer\n vector<string> res;\n \n //extract columns and rows\n int col1= s[0]-\'A\' , col2= s[3]-\'A\';\n int row1= s[1]-\'0\' , row2= s[4]-\'0\';\n \n //keep incrementing the character from c1->c2\n for(;col1<=col2;col1++){\n char letter= col1+\'A\'; \n //for every charcter traverse from r1->r2 \n for(int i=row1;i<=row2;i++){\n string p="";\n char r= i+\'0\'; //get corresponding column in terms of character\n p+=letter; //append current column-> letter\n p+=r; //append current row\n res.push_back(p); //put string in res vector\n } \n }\n return res;\n }
108,040
Cells in a Range on an Excel Sheet
cells-in-a-range-on-an-excel-sheet
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
String
Easy
From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order.
648
5
```\nclass Solution {\n public List<String> cellsInRange(String s) {\n List<String> ans = new ArrayList<String>();\n for(char i = \'A\' ; i <= \'Z\'; ++i) {\n for(char j = \'1\'; j <= \'9\'; ++j) {\n if(i >= s.charAt(0) && i <= s.charAt(3) && j >= s.charAt(1) && j <= s.charAt(4)){\n ans.add(Character.toString(i) + Character.toString(j));\n }\n }\n }\n return ans;\n }\n}\n```
108,046
Cells in a Range on an Excel Sheet
cells-in-a-range-on-an-excel-sheet
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
String
Easy
From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order.
1,390
12
```\nclass Solution {\n public List<String> cellsInRange(String str) {\n char[] s = str.toCharArray();\n List<String> result = new ArrayList<>();\n for (char c1 = s[0]; c1 <= s[3]; c1++) {\n for (char c2 = s[1]; c2 <= s[4]; c2++) {\n result.add("" + c1 + c2);\n }\n }\n return result;\n }\n}\n\n```
108,049
Cells in a Range on an Excel Sheet
cells-in-a-range-on-an-excel-sheet
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
String
Easy
From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order.
500
7
```\nclass Solution {\npublic:\n vector<string> cellsInRange(string s) \n {\n char ch1 = s[0], ch2 = s[3]; // stroing 0th and 3rd char [A1:B2] , 0th=A , 3rd=B\n int in1= s[1]-\'0\', in2=s[4]-\'0\'; // stroing 1st and 4th int [A1:B2] , 1st=1 , 4th=2\n vector<string> ans;\n \n for(int i=ch1-\'A\'; i<=ch2-\'A\'; i++)\n {\n for(int j=in1; j<=in2; j++)\n {\n string s= ch1+to_string(j);\n ans.push_back(s);\n }\n ch1 = ch1+1;\n }\n return ans; \n }\n};\n```
108,050
Cells in a Range on an Excel Sheet
cells-in-a-range-on-an-excel-sheet
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
String
Easy
From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order.
1,243
10
Please pull this [commit]() 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])+1)]\n```
108,055
Cells in a Range on an Excel Sheet
cells-in-a-range-on-an-excel-sheet
A cell (r, c) of an excel sheet is represented as a string "<col><row>" where: You are given a string s in the format "<col1><row1>:<col2><row2>", where <col1> represents the column c1, <row1> represents the row r1, <col2> represents the column c2, and <row2> represents the row r2, such that r1 <= r2 and c1 <= c2. Return the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
String
Easy
From the given string, find the corresponding rows and columns. Iterate through the columns in ascending order and for each column, iterate through the rows in ascending order to obtain the required cells in sorted order.
127
5
```\nimpl Solution {\n pub fn cells_in_range(s: String) -> Vec<String> {\n let sb = s.as_bytes();\n (sb[0]..=sb[3])\n .flat_map(|col| (sb[1]..=sb[4]).map(move |row| format!("{}{}", col as char, row as char)))\n .collect()\n }\n}\n```
108,057
Append K Integers With Minimal Sum
append-k-integers-with-minimal-sum
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.
Array,Math,Greedy,Sorting
Medium
The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.
10,962
128
What a tricky problem. We sort numbers, and then swipe the range from 1 to 10^9, appending numbers that do not appear in the array.\n \nHowever, this will cause TLE, since `k` can be very large.\n\nWhat we can do is to compute the minimal possible sum as `k * (k + 1) / 2)`. Then, we go through *unique* numbers in the array, and substitute all numbers less than, or equal `k`, with increasing numbers greater than `k`.\n\n**C++**\n```cpp\nlong long minimalKSum(vector<int>& nums, int k) {\n long long res = (long long)k * (k + 1) / 2;\n for (int n : set<int>(begin(nums), end(nums)))\n if (n <= k)\n res += (++k) - n;\n return res;\n}\n```\n#### Optimized Version\nHere we use in-place heap, and exit early if there are no more numbers `<= k`. Compared to the above, the runtime is improved by ~100 ms.\n**C++**\n```cpp\nlong long minimalKSum(vector<int>& nums, int k) {\n long long res = (long long)k * (k + 1) / 2, last = 0;\n make_heap(begin(nums), end(nums), greater<int>());\n while (!nums.empty() && nums.front() <= k) {\n int n = nums.front();\n pop_heap(begin(nums), end(nums), greater<int>()); nums.pop_back();\n if (n != last) \n res += (++k) - n;\n last = n;\n }\n return res;\n}\n```\n#### Original Solution\nSame idea, but longer/less efficient. We use gaps between sorted numbers to compute the sum.\n**C++**\n```cpp\nlong long minimalKSum(vector<int>& nums, int k) {\n long long res = 0, cur = 1;\n nums.push_back(INT_MAX);\n sort(begin(nums), end(nums));\n for (int i = 0; k > 0 && i < nums.size(); ++i) {\n int take = max(0, min(k, nums[i] - (int)cur));\n res += (cur + take) * (cur + take - 1) / 2 - cur * (cur - 1) / 2;\n k -= take;\n cur = (long long)nums[i] + 1;\n }\n return res;\n}\n```
108,063
Append K Integers With Minimal Sum
append-k-integers-with-minimal-sum
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.
Array,Math,Greedy,Sorting
Medium
The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.
5,128
86
\n\n#### Assume that the gaps between integers in **A** are empty cells, one for each unique integer.\n\nIn order to get the minimum sum, we need to fill the empty cell in ascending order.\nFor example.\n![image]()\n\nWe definitely don\'t want to fill these cells one by one.\n\n<br/> \n\n#### Any better approaches than brute force?\nWe can find the first integer (**A[i]** for example) in A, such that **A[i]** has enough empty cells on its left. Thus the total sum equals **(k + i)\\*(k + i + 1)/2 - sum(A[:i])** , where the second term equals the sum of numbers in A which are smaller than **A[i]**. \n\nTake the picture below as an example, assume k = 5, cells 1-8 are filled with either the original integers from **A** or the inserted integers. \n\n![image]()\n\n#### How to find the first **A[i]**?\n\nGiven an input array with unique integers ```A```, how many empty cells to the left of ```A[i]```?\n![image]()\n\nWe can find the first integer in ```A``` that has enough empty cells for ```k``` numbers, with brute-force iteration.\n> More specifically: \n> - A[0] = 2 and has 1 empty cell to its left.\n> - A[1] = 4 and has 2 empty cells to its left.\n> - A[2] = 7 and has 4 empty cells to its left.\n> - ... \n> - A[3] = 10 and has 6 empty cells to its left which are enough to hold k(5) numbers.\n> - A[3] is the **first integer** in A that has enough empty cells on its left.\n\n![image]()\n\nWe won\'t use linear time iteration, but use Binary Search to locate this integer in logarithmic time (doesnt affect the overall time complexity)\n\n**(The binary search is NOT necessary, we can just iterate over all A[i]\'s until we find the first valid i. \nThanks to whoever corrected me. \nPlease also refer to [votrubac\'s solution](*-(n-%2B-1)-2) or other top solutions!)**\n\n<details>\n<summary> Original binary search (NOT necessary) </summary> \n![image]()\n\nIf the A[middle] has less than k empty cells on its left, we move on to the right half, otherwise, we move on to the left half.\n\n</details> \n \n<br/> \n<br/> \n \n \n\t\n#### What to do when we find the A[i]?\n\nRecall the second picture:\n> - We want to insert 5 integers.\n> - A[3] = 10 is the **first integer** having enough(>=5) empty cells on its left.\n> - There are **3** elements in A which is smaller than 10 (Since A[3] = 10).\n> - **3+5=8**, thus, integers 1 - 8 are filled by either original elements from A, or the inserted integers.\n> - The inserted sum equals: **1+2+...+8 - sum(A[:3])**\n> \n\n![image]()\n\n#### Some Tips\n- **A** might contain duplicate numbers, get the unique integers first.\n- If the largest element in **A** doesn\'t have enough cells on its left, it equals that we filled every integer from 1 to k + len(A), then the total sum equals: 1+2+3+...+(k+len(A)) - sum(A).\n\n```\ndef minimalKSum(self, A: List[int], k: int) -> int:\n A = sorted(list(set(A)))\n n = len(A)\n \n if A[n - 1] <= k + n:\n return (k + n) * (k + n + 1) // 2 - sum(A)\n\n lft, rgt = 0, n - 1\n while rgt > lft:\n mid = (lft + rgt) // 2\n if A[mid] - mid <= k:\n lft = mid + 1\n else:\n rgt = mid\n\n return (k + lft) * (k + lft + 1) // 2 - sum(A[:lft])\n```\n\n
108,064
Append K Integers With Minimal Sum
append-k-integers-with-minimal-sum
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.
Array,Math,Greedy,Sorting
Medium
The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.
4,992
55
```\nclass Solution {\npublic:\n long long minimalKSum(vector<int>& nums, int k){\n sort(nums.begin(), nums.end());\n long long s = 0;\n int i = 0;\n int prev = 0;\n while(k>0 && i<nums.size()){\n int len = nums[i] - prev - 1;\n if(len>k) len = k;\n if(len>0){\n long long int start = prev;\n long long int end = start + len;\n long long int sum = (end*(end+1))/2 - (start*(start+1))/2;\n s += sum;\n k -= len;\n }\n prev = nums[i]; i++;\n }\n if(k>0){\n long long int start = prev;\n long long int end = start + k;\n long long int sum = (end*(end+1))/2 - (start*(start+1))/2;\n s += sum;\n }\n return s;\n }\n};\n```\n*If you like the solution, please Upvote \uD83D\uDC4D!!*
108,065
Append K Integers With Minimal Sum
append-k-integers-with-minimal-sum
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.
Array,Math,Greedy,Sorting
Medium
The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.
4,308
48
\n Arrays.sort(nums);\n Set<Integer> set = new HashSet<>();\n long sum = 0;\n \n for (int num: nums) {\n if (!set.contains(num) && num <= k) {\n k++;\n sum += num; \n } \n set.add(num);\n }\n \n long res = (long)(1 + k) * k / 2 - sum;\n return res; \n }
108,066
Append K Integers With Minimal Sum
append-k-integers-with-minimal-sum
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.
Array,Math,Greedy,Sorting
Medium
The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.
3,189
31
\nSee my latest update in repo [LeetCode]()\n\n## Solution 1. Sorting\n\n**Intuition**: Sort the array. Traverse from left to right, sum up the missing numbers between `A[i-1]` and `A[i]` until we\'ve used `k` missing numbers.\n\n**Algorithm**:\n\nFor a given `A[i]`, the previous number `prev` is `A[i-1]` or `0` if `A[i-1]` doesn\'t exist.\n\nThere are `cnt = min(k, max(0, A[i] - prev - 1))` missing numbers inbetween, i.e. from `prev+1` to `prev+cnt`. The sum of these numbers is `(prev+1 + prev+cnt) * cnt / 2`.\n\nIf there are still `k` missing numbers after traversing the array, the rest of the missing numbers are `A[N-1]+1` to `A[N-1]+k`. The sum of them is `(A[N-1]+1 + A[N-1]+k) * k / 2`.\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(NlogN)\n// Space: O(1)\nclass Solution {\npublic:\n long long minimalKSum(vector<int>& A, int k) {\n sort(begin(A), end(A));\n long ans = 0, N = A.size();\n for (int i = 0; i < N && k; ++i) {\n long prev = i == 0 ? 0 : A[i - 1]; // the previous number\n long cnt = min((long)k, max((long)0, A[i] - prev - 1)); // the count of missing numbers between `prev` and `A[i]`\n k -= cnt; // use these `cnt` missing numbers\n ans += (long)(prev + 1 + prev + cnt) * cnt / 2; // sum of these `cnt` missing numbers `[prev+1, prev+cnt]`.\n }\n if (k > 0) ans += ((long)A.back() + 1 + A.back() + k) * k / 2; // If there are still missing numbers, add the sum of numbers`[A.back()+1, A.back()+k]` to answer\n return ans;\n }\n};\n```
108,067
Append K Integers With Minimal Sum
append-k-integers-with-minimal-sum
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.
Array,Math,Greedy,Sorting
Medium
The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.
1,050
23
For the test case `[1000000000] 1000000000`, the output should be `500000000500000001`. But in JS, we can\'t have such a big number during general calculation.\n\nI know we could use `BigInt`, and I did it also. But, no matter I return the final BigInt `500000000500000001n` or I convert it into string `500000000500000001`, the judge will always show my answer is `500000000500000000` and tell me it\'s wrong. __Seems like the judge always try to convert the result into a general number in JS.__\n\nAfter several times, I finally have to implement this in another language... T_T\n\nTo fix this, the solution is easy, for this problem in JS judge, it could try to __accept the `BigInt` result__.\n\nThe core strategy is simple, but maybe next time judge could try to think about such big number testcase in JS more.\nI guess the purpose for this problem is not to ask us to implement our own bigint calculation in JS, haha\n\n- - -\n\nUPDATE:\n\nI\'ve submitted this problem to [official github repo here]().\n\n- - -\n\nUPDATE:\n\nThe test cases have been updated - added a limitation. So right now, we could use JS to make this problem AC.\n\nThe core strategy is:\n- assume all the numbers from 1 to `k` is unused, so we could get the init `sum`\n- count the numbers smaller than `k` in `nums` and minus them from `sum`\n- add new numbers from `k + 1` to meets the count `k` (take care of the new number is in `nums`)\n\nHere\'s a sample code from me:\n\n```js\nconst minimalKSum = (nums, k) => {\n const set = new Set(nums);\n let sum = (1 + k) * k / 2;\n let more = 0;\n nums = Array.from(set)\n for (const n of nums) {\n n <= k && (++more, sum -= n);\n }\n while (more > 0) {\n !set.has(++k) && (sum += k, --more);\n }\n return sum;\n};\n```
108,069
Append K Integers With Minimal Sum
append-k-integers-with-minimal-sum
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.
Array,Math,Greedy,Sorting
Medium
The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.
1,292
8
**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 value as start and i+1th value as end\n4. In the current iteration we will be adding values b/w start and end as long as k does\'nt expire\n5. If start == end then continue\n6. Now we sill be using the values start+1, start+2 ... end -2, end-1. We would not use the values start and end themselves.\n7. We know that sum of consecutive integers is given by the AP formula with `d = 1`\n8. Add this sum to the result and remove the number of integers used from k\n\n**Why I added 0 and 2000000001:**\nSince the +ve integers start from 1, and it is not certain that the list might start from 1. We should manually take care of the smallest elements to add so as to minimize the possible sum. So I added 0 to allow it to blend in with the algorithm perfectly.\nThe reason I added 2000000001 is to prevent ourselves from running out of +ve numbers even when all k havent expired\n\n**Formula for sum in AP (arithmetic progression)**\nThe sum of given AP `a, a+d, a+2d, a+3d ... a+(i-1)d ... a+(n-1)d` is:\n`S = n/2[2a + (n \u2212 1) \xD7 d]` where a is the first term and n is the total number of terms in AP\n*In our case since we will be dealing with consecutive numbers `d = 1`*\n\n```\nclass Solution:\n def minimalKSum(self, nums: List[int], k: int) -> int:\n nums.sort()\n res = 0\n nums.insert(0, 0)\n nums.append(2000000001)\n n = len(nums)\n for i in range(n-1):\n start = nums[i] # This is the lowerbound for current iteration\n end = nums[i+1] # This is the higherbound for current iteration\n if start == end:\n continue\n a = start + 1 # Starting value is lowerbound + 1\n n = min(end - start - 1, k) # Since the total number possible b/w start and end might be more than the k numbers left, so always choose the minimum.\n v = (n*(2*a + n - 1))//2 # n/2[2a + (n-1)d] with d = 1\n res += v # Add the sum of elements selected into res\n k -= n # n number of k\'s expired, thus k decrements\n return res\n```
108,070
Append K Integers With Minimal Sum
append-k-integers-with-minimal-sum
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.
Array,Math,Greedy,Sorting
Medium
The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.
1,952
17
**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 public long minimalKSum(int[] nums, int k) {\n Arrays.sort(nums);\n long ans = 0, lo = 1;\n for (int num : nums) {\n if (num > lo) {\n long hi = Math.min(num - 1, lo + k - 1);\n int cnt = (int)(hi - lo + 1);\n ans += (lo + hi) * cnt / 2;\n k -= cnt;\n if (k == 0) {\n return ans;\n }\n } \n lo = num + 1;\n }\n if (k > 0) {\n ans += (lo + lo + k - 1) * k / 2;\n }\n return ans;\n }\n```\n```python\n def minimalKSum(self, nums: List[int], k: int) -> int:\n ans, lo = 0, 1\n cnt = 0\n for num in sorted(nums):\n if num > lo:\n hi = min(num - 1, k - 1 + lo)\n cnt = hi - lo + 1\n ans += (lo + hi) * cnt // 2 \n k -= cnt\n if k == 0:\n return ans\n lo = num + 1\n if k > 0:\n ans += (lo + lo + k - 1) * k // 2\n return ans\n```\n\n----\n\n**Method 2:**\n\nStart from the sum of `1` to `k`, `ans`, then traverse the sorted distinct numbers of input array, `nums`; whenever find a `num` not greater than `k`, we need to deduct it from `ans` and add `++k`.\n\n\n```java\n public long minimalKSum(int[] nums, int k) {\n long ans = k * (k + 1L) / 2;\n TreeSet<Integer> unique = new TreeSet<>();\n for (int num : nums) {\n unique.add(num);\n }\n while (!unique.isEmpty()) {\n int first = unique.pollFirst();\n if (k >= first) {\n ans += ++k - first;\n }\n }\n return ans;\n }\n```\n\n```python\nfrom sortedcontainers import SortedSet\n\nclass class:\n def minimalKSum(self, nums: List[int], k: int) -> int:\n ans = k * (k + 1) // 2\n for num in SortedSet(nums):\n if k >= num:\n k += 1\n ans += k - num\n return ans\n```\n**Analysis:**\n\nTime: `O(nlogn)`, space: `O(n)` - including sorting space, where `n = nums.length`.
108,071
Append K Integers With Minimal Sum
append-k-integers-with-minimal-sum
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.
Array,Math,Greedy,Sorting
Medium
The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.
2,269
22
```\nclass Solution {\npublic:\n long long minimalKSum(vector<int>& nums, int k) {\n long ans=(long(k)*(long(k+1)))/2;\n // be sure to use unique numbers in nums\n unordered_set<int>st(nums.begin(),nums.end());\n nums.clear();\n for(auto &i:st)\n nums.push_back(i);\n // sort nums\n sort(begin(nums),end(nums));\n int sz=nums.size();\n // iterate over the array\n for(int i=0;i<sz;i++){\n // if you have added a number in nums that was already present in nums then remove that and add next candidate that is k+1\n if(nums[i]<=k ){\n ans-=nums[i];\n ans+=k+1;\n k++;\n }\n else\n break;\n }\n return ans;\n }\n};\n```\nDo **UPVOTE** if it thelps :)
108,072
Append K Integers With Minimal Sum
append-k-integers-with-minimal-sum
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.
Array,Math,Greedy,Sorting
Medium
The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.
619
6
So first I came up with this approach during contest,\nStart from 1 and keep adding the first k-missing integers into results, but it would cost O(k) time at most.\n\n**For example :**\nnums[1,100000] and k = 1e9\nSo in this case we will be adding 1e9-2 elements. So intution behind O(k) will give TLE because k is very large.\n\nSo, let\'s think again what we did which cause TLE.\nSuppose,\nnums[i] = x\nnums[i+1] = y\n\nx<y than atmost y-x-1 element we can add it right? Now we break the problem i.e. from going i-th index to i+1\'th index it would be cost sum[x+1....y). Now is there any way to get this sum fastly?\n1. Since we can jump from i-th point to i+1\'th point only when x<=y. And problem description is not intreseted with order so let\'s short it.\n2. Now we did sorting. So we know that from going i-th index to i+1\'th index { sum[x+1....y) } all the element will be contigues elements. So we know that how max element we can add into this gap and we can get the sum easily using sum of AP series. i.e.\n\t\t*(n/2)*[2*a+(n-1)*d]*\n\t\t* Where \'n\' will be nums[i+1]-nums[i] for every i index.\n\t\t* \'a\' will be the first element( we\'ll start adding from nums[i]+1 so a=nums[i]+1).\n\t\t* \'d\' will be 1 because for min sum we\'ll keep adding continuos elements.\n```\nclass Solution {\npublic:\n long long getApSum(long long a, long long n, long long d) {\n return ((2*a+(n-1)*d)*n)/2;\n }\n long long minimalKSum(vector<int>& nums, int k) {\n long long res=0;\n \n // To use first element also. Like if nums start with 5 than we can add [1,2,3,4]\n nums.push_back(0);\n sort(nums.begin(), nums.end());\n \n // Keep adding till k\n for(int i=0;i<nums.size()-1 && k>0;i++) {\n \n // Get the length of AP which can be added.\n int n = nums[i+1]-nums[i]-1;\n \n // If we can\'t add any element, for example [12,12] or [11,12].\n if(n<=0) continue;\n \n // If we have option to add much more than needed. For example [1,12] and k is 5. So we need only 5 element to add.\n if(k<n) n=k;\n k-= n;\n \n // Get the sum of n AP elements who\'s first element is nums[i]+1 and keep difference of 1.\n res += getApSum(nums[i]+1, n, 1);\n }\n \n // If still we k to add element than add continuous k element from nums.back()+1.\n // For example : nums[1,2] and k=5 So we need add [3,4,5,6,7].\n if(k>0) {\n res+= getApSum(nums.back()+1, k, 1);\n }\n return res;\n }\n};\n```\t\n\n# Time Complexity :\n**It\'s O(N*log N), Since we are just doing sorting. Getting N-element AP sum takes constant time.**\n# Space Complexity :\n**Since we are not using any extra space. So it\'s constant space.**\n\n**Please upvote if it helps you.**\n*Happy Coding :)*
108,073
Append K Integers With Minimal Sum
append-k-integers-with-minimal-sum
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.
Array,Math,Greedy,Sorting
Medium
The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.
717
16
**Intuition :**\n\n* Idea here is pretty straightforward. Since we need to get sum as minimal,\n\n* We have to choose smallest element first\n* And in order to get smallest elements, we need to sort `nums` first.\n* Then we append element that are between say **`(prev, curr)`** (exclusive).\n* In this way, we can get smallest element first. (starting from 0)\n* We need to take care of case when all elements in array are finished,\n\t* And we have few elements left to append.\n\t* In this case we append element starting from prev till remaining number of elements.\n\n\n\t\t\t\tEx: nums = [5, 6], k = 6\n\n\t\t\t\t\t -> prev here is 0, starting point\n\n\t\t\t\t1. i=0 , k = 6, prev = 0, curr = 5, diff = 5-0-1 = 4\n\t\t\t\t\t-> thus we choose element b/w (0, 5) i.e { 1,2,3,4 }.\n\t\t\t\t\t\t-> sum = 1+2+3+4 = 10\n\t\t\t\t\t\t-> k = k - diff = 6 - 4 = 2\n\t\t\t\t\t\t-> prev = 5\n\n\t\t\t\t2. i =1, k = 2, prev = 5, curr = 6, diff = -1, \n\t\t\t\t\t-> since diff is negative, we cannot get elements b/w (5, 6)\n\t\t\t\t\t-> update, prev = 6\n\n\t\t\t\tNow, we have no elements in nums left, and k is also not 0,\n\t\t\t\tSo we need to add k = 2, more element from prev\n\t\t\t\t\ti.e (6, 6+3) = (6, 9) => {7, 8}\n\n\t\t\t\t\t-> sum = 10 + 7 + 8 = 25\n\t\t\t\n# Code :\n\n```\nclass Solution {\npublic:\n long long minimalKSum(vector<int>& nums, int k) {\n int n = nums.size();\n \n // Sort array so that we can get smaller elements first\n sort(begin(nums), end(nums));\n \n long long sum = 0;\n \n // Previous element that we encountered\n int prev = 0, curr = 0;\n \n for(int i=0; i<n; i++) {\n \n curr = nums[i];\n \n // Get the difference b/w prev and current \n // So that we can append elements that are in between them\n long long diff = (curr - prev - 1);\n \n // If prev and current are same then just skip\n if(diff <= 0) {\n prev = curr;\n continue;\n }\n \n // If there are more available elements b/w prev and current\n // Then we just take closest k element from prev.\n // And leave remaining as it is\n if(diff > k) {\n diff = k;\n curr = prev + k + 1;\n }\n \n // Get the sum of all elements b/w prev and current\n // Since it is AP series, we can use direct formula\n sum += (diff * 1LL * (curr + prev) / 2);\n \n // Update previous to current\n prev = curr;\n \n // Update count of how many more element we need to append \n k -= diff;\n \n if(k == 0) break;\n }\n \n // Case : When we have reached the end of array \n // And still we have some more element left to append\n if(k) {\n sum += (k * 1LL * (2 * prev + k + 1) / 2);\n }\n \n return sum;\n }\n};\n```\n\n**Complexity :**\n\n* Time : `O(NlogN + N)`, N is size of `nums` array\n\t* To sort the array first\n\t* And then iterate over to get sum \n\n* Space : `O(1)`\n\n***If you find this helpful, do give it a like :)***
108,074
Append K Integers With Minimal Sum
append-k-integers-with-minimal-sum
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.
Array,Math,Greedy,Sorting
Medium
The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.
910
10
Please pull this [commit]() 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 if prev < x: \n if x <= k: \n k += 1\n ans += k - x\n else: break\n prev = x\n return ans \n```
108,077
Append K Integers With Minimal Sum
append-k-integers-with-minimal-sum
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.
Array,Math,Greedy,Sorting
Medium
The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.
1,112
15
1. We only need to get the minimum sum of k values need to be inserted.\n2. We will use n*(n+1)/2 to calculate the sum upto k values.\n3. We will delete the value that is present in the array and add the next k+1 value to the sum.\n4. We have to handle the duplicate value case So we will use Set.\n5. Set will sort the array and give the unique elements in it. \n\n``` \nlong long minimalKSum(vector<int>& nums, int k) { \n set<int>s(nums.begin(),nums.end());\n long long ans = (long(k)*(long(k+1)))/2; \n for(auto i:s){\n if(i<=k){ \n ans+=k+1;\n ans-=i;\n k++;\n }\n else \n break;\n }\n return ans;\n }\n```\n\n**PLEASE UPVOTE IF YOU LIKE AND USE CODE. ; )**
108,078
Append K Integers With Minimal Sum
append-k-integers-with-minimal-sum
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.
Array,Math,Greedy,Sorting
Medium
The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.
519
8
**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 take care of case when all numbers in array/list is finished but we still need to append some numbers.\n* Now in this case we will append numbers starting from `prev` till remaining numbers.\n\n**Example:**\nFirst Case:\n```\nnums = [1,4,25,10,25], k = 2\nSo let\'s first sort nums.\nnums=[1,4,10,25,25]\n\nNow prev=0 # starting point\ncurr=nums[0]=1 \nNow there is no number betwenn (prev,curr) that we can add in array/list.\nSo, move curr to next elemnt of nums and prev to curr.\n\nprev=1\ncurr=4\n(prev,curr)=2,3\nsum=2+3=5\nSo add 2 and 3. Now k become 0 so stop the process.\n\nAnd return sum.\n```\n\nSecond case:\n```\nnums = [5,6], k = 6\nso let\'s first sort nums.\nnums=[5,6]\n\nNow prev=0 # starting point\ncurr=nums[0]=5\n(prev,curr)=1,2,3,4\nsum=1+2+3+4=10\nk=2\nAs k is not 0 continue the process.\n\nNow prev=curr=5\ncurr=nums[1]=6\nNow there is no number betwenn (prev,curr) that we can add in array/list.\n\nnow prev=curr=6\nbut now we finished all numbers of nums. but still we need to add two more numbers.\nwe do not have number to update curr.\n\nSo, now start from prev and continue adding numbers untill k becomes zero.\nnumbers=7,8\n\nsum=sum+7+8\n =10+7+8\n =25\n\nand k=0\nreturn sum\n```\n\n**Note:**\nWe can\'t just iterate from all numbers between prev and curr to find sum of added number. As it might give TLE. So we can use formula for sum of Arithmetic Progression. As number between prev and curr will be in Arithmetic Progression with difference 1.\n\n**Formula for sum of AP:**\n```\nFormula 1: n/2(a + l)\nwhere,\nn = number of terms\na=first term\nl=last term\n\nFormula 2: n/2[2a + (n \u2212 1) \xD7 d]\nWhere, \nn = number of terms\na=first term\nd=difference between two term\n```\n\nWe will be using this formula to find sum betwenn (prev,curr).\n\n**Code:**\n```\nclass Solution:\n def minimalKSum(self, nums: List[int], k: int) -> int:\n n=len(nums)\n curr=prev=0 # intialize both curr and prev \n nums.sort() # sort the nums\n sum=0 \n for i in range(n):\n curr=nums[i] # make curr equal to prev\n diff=curr-(prev+1) # find if there is any numbers in (prev,curr)\n if diff<=0: # if no then update prev and continue \n prev=curr\n continue\n if diff>k: # if yes then if number between (prev,curr) is more then k \n diff=k # then we will consider first k numbers only\n curr=prev+1+k # update curr to last number that we will add to use formula 1 of A.P.\n sum+=(diff*(curr+prev)//2) # formula 1 of A.P.\n prev=curr # update prev to curr\n k-=diff # update k\n if k==0: # if k is 0 then return\n break\n if k: # second case # we have finish nums but wnat to add more numbers\n sum+=(k*(2*prev+k+1)//2) # use formual 2 of A.P. we take d=1\n return sum\n```\nUpvote if you find it helpful :)
108,080
Append K Integers With Minimal Sum
append-k-integers-with-minimal-sum
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.
Array,Math,Greedy,Sorting
Medium
The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.
422
9
1. Get the sum of first k natural numbers \n \n2. make a min heap , insert nums in the heap\n \n3. now if the smallest number in heap is less than or equal to k ,we need to delete that number from our sum and add some greater value\n \n4. subtract top from sum and after incrementing k , add the new value of k to sum \n \n example : nums=[1,3,5] , k=4\n \n sum = 1+2+3+4= (4*(4+1))/2 = 10 \n \n but here 1 is in nums so we need to subtract 1 from sum and add (k+1)\n k=k+1 -> k=5\n sum=sum-1+5 -> sum= 10-1+5 = 14\n \n now , top of heap is 3 \n k=5+1=6\n sum=14-3+6=17\n \n now , top of the heap is 5\n k=6+1=7\n sum=17-5+7=19\n \n answer is 19 . \n\n\n```\n\n\nclass Solution {\npublic:\n long long minimalKSum(vector<int>& nums, int k) {\n \n priority_queue<int,vector<int>,greater<int>> pq;\n long long sum=((long long)k*(k+1))/2;\n \n \n for(int x:nums){\n pq.push(x);\n }\n \n while(!pq.empty() && k>=pq.top()){\n \n k=k+1;\n int temp=pq.top();\n pq.pop();\n while(!pq.empty() && temp==pq.top()){\n pq.pop();\n }\n sum=sum-temp+k;\n }\n \n return sum;\n }\n};\n```\n\n**I\'m new here . Please UPVOTE if you like my solution , DOWNVOTE otherwise **
108,082
Append K Integers With Minimal Sum
append-k-integers-with-minimal-sum
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.
Array,Math,Greedy,Sorting
Medium
The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.
472
5
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 list contains 20 and 25, then k will become 52, and we calculate the sum of the 52 first numbers, then we remove 20 + 25 because they were already existing.\n```python\ndef minimalKSum(self, nums: List[int], k: int) -> int:\n\tnums = list(set(nums)) # to remove duplicated numbers\n\tnums.sort() # sorting the new list\n\tlast_term = k\n\tremovable_sum = 0\n\tfor num in nums :\n\t\tif (num <= last_term) : # if the current number is in the range of the k first numbers\n\t\t\tlast_term += 1 # we increment the last number we\'re going to add\n\t\t\tremovable_sum += num # adding the current number the sum of existing numbers\n\t\telse :\n\t\t\tbreak # if we found the k th number we break the loop\n\tsomme = (last_term * (1 + last_term) / 2) - removable_sum # we calculate the sum of the arithmetic sequence minus the sum of the existing numbers\n\treturn int(somme)\n```
108,083
Append K Integers With Minimal Sum
append-k-integers-with-minimal-sum
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.
Array,Math,Greedy,Sorting
Medium
The k smallest numbers that do not appear in nums will result in the minimum sum. Recall that the sum of the first n positive numbers is equal to n * (n+1) / 2. Initialize the answer as the sum of 1 to k. Then, adjust the answer depending on the values in nums.
398
5
As the constraints are high (<= 10^9) this problem will give either TLE or MLE if we go through each and every element in this range.\n\nWhat we can do is calculate sum of first k consecutive integers initially.\nThen if we find that element in the array, we would delete it and append a new max possible number.\n\nEx:\narr: 2 3 5 7 10\nk: 4\nHere, \nsum = 1 + 2 + 3 + 4 = 4 * 5 / 2 = 10\nlast = 5\nans (should be) = 1 + 4 + 6 + 8 = 19\n```\nfor(i = 0 to size - 1)\n{\n\tif(element_already_present_in_array)\n\t{\n\t\tsum -= element;\n\t\tsum += last_element;\n\t}\n}\n```\ni = 0 sum -= 2; sum += 5; // sum = 13\ni = 1 sum -= 3; sum += 6; // sum = 16\ni = 2 sum -= 5; sum += 7; // sum = 18\ni = 3 sum -= 7; sum += 8; // sum = 19\ni = 4 do nothing as the element is greater than last max element which was needed\n\n**CODE:**\n```\nlong long minimalKSum(vector<int>& nums, int k) {\n long long sum = (long long)k * (k + 1) / 2;\n\t\tlong long last = k + 1;\n sort(nums.begin(), nums.end());\n \n for(int i = 0; i < nums.size(); ++i)\n {\n if(i > 0 && nums[i] == nums[i - 1])\n continue;\n \n if(nums[i] < last)\n {\n sum -= nums[i];\n sum += last++;\n }\n }\n return sum;\n }\n```
108,084
Create Binary Tree From Descriptions
create-binary-tree-from-descriptions
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, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid.
Array,Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node.
6,087
135
We are using a hashmap (**getNode**) to store node for corresponding value. Also, we are using a hashmap (**isChild**) to check if node is a child or not.\nThen, we traverse through the *descriptions* array and make the connections accordingly.\n* If we haven\'t created node for corresponding value previously we create it otherwise we get the node from hashmap (*getNode*).\n* We connect the child node to parent node as a left or right child according to the value of isLeft.\n* And mark child node as *true* in hashmap (*isChild*).\n\nAt last we travel through all the nodes in *descriptions* to check which node has no parent (i.e root node) and return the root node.\n*descriptions[i] = [parent, child, isLeft]*\nI am checking for only parent because checking child node makes no sense and saves some time.\n\n```\nclass Solution {\npublic:\n TreeNode* createBinaryTree(vector<vector<int>>& descriptions){\n unordered_map<int, TreeNode*> getNode; //to check if node alredy exist\n unordered_map<int, bool> isChild; //to check if node has parent or not\n for(auto &v: descriptions){\n if(getNode.count(v[0])==0){\n TreeNode* par = new TreeNode(v[0]);\n getNode[v[0]] = par;\n }\n if(getNode.count(v[1])==0){\n TreeNode* child = new TreeNode(v[1]);\n getNode[v[1]] = child;\n }\n if(v[2]==1) getNode[v[0]]->left = getNode[v[1]]; //left-child\n else getNode[v[0]]->right = getNode[v[1]]; //right-child\n isChild[v[1]] = true;\n }\n TreeNode* ans = NULL;\n for(auto &v: descriptions){\n if(isChild[v[0]] != true){ //if node has no parent then this is root node\n ans = getNode[v[0]]; \n break;\n }\n }\n return ans;\n }\n};\n```\n*If you like the solution, please Upvote \uD83D\uDC4D!!*
108,113
Create Binary Tree From Descriptions
create-binary-tree-from-descriptions
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, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid.
Array,Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node.
4,066
70
```\npublic TreeNode createBinaryTree(int[][] descriptions) {\n HashMap<Integer, TreeNode> map = new HashMap<>();\n Set<Integer> children = new HashSet<>();\n for (int[] arr : descriptions) {\n int parent = arr[0], child = arr[1], isLeft = arr[2];\n children.add(child);\n TreeNode node = map.getOrDefault(parent, new TreeNode(parent));\n if (isLeft == 1) {\n node.left = map.getOrDefault(child, new TreeNode(child));\n map.put(child, node.left);\n } else {\n node.right = map.getOrDefault(child, new TreeNode(child));\n map.put(child, node.right);\n }\n map.put(parent, node);\n }\n \n int root = -1;\n for (int [] arr: descriptions) {\n if (!children.contains(arr[0])) {\n root = arr[0];\n break;\n }\n }\n \n return map.getOrDefault(root, null);\n }\n\n```
108,114
Create Binary Tree From Descriptions
create-binary-tree-from-descriptions
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, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid.
Array,Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node.
2,463
30
See my latest update in repo [LeetCode]()\n\n## Solution 1. Hash Table\n\nMaintain a hash map from node value to node pointer. Use this map to prevent creating the same node multiple times.\n\nTo get the root node, we can maintain another map `parentMap` mapping from child node pointer to parent node pointer. We pick a random node pointer and keep traversing back towards the root using `parentMap` until the node doesn\'t have any parents.\n\n```cpp\n// OJ: \n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(N)\nclass Solution {\npublic:\n TreeNode* createBinaryTree(vector<vector<int>>& A) {\n unordered_map<TreeNode*, TreeNode*> parentMap; // map from child node pointer to parent node pointer\n unordered_map<int, TreeNode*> m; // map from node value to node pointer\n for (auto &v : A) {\n int p = v[0], c = v[1], isLeft = v[2];\n auto parent = m.count(p) ? m[p] : (m[p] = new TreeNode(p));\n auto child = m.count(c) ? m[c] : (m[c] = new TreeNode(c));\n if (isLeft) parent->left = child;\n else parent->right = child;\n parentMap[child] = parent;\n }\n auto root = m.begin()->second; // Pick a random node pointer and keep traversing up until the node doesn\'t have any parents\n while (parentMap.count(root)) root = parentMap[root];\n return root;\n }\n};\n```
108,116
Create Binary Tree From Descriptions
create-binary-tree-from-descriptions
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, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid.
Array,Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node.
3,514
48
# **Explanation**\nIterate `descriptions`,\nfor each `[p, c, l]` of `[parent, child, isLeft]`\n\nCreate `Treenode` with value `p` and `c`,\nand store them in a hash map with the value as key,\nso that we can access the `TreeNode` easily.\n\nBased on the value `isLeft`,\nwe assign `Treenode(parent).left = Treenode(child)`\nor `Treenode(parent).right = Treenode(child)`.\n\nFinall we find the `root` of the tree, and return its `TreeNode`.\n<br>\n\n**Python**\n```py\n def createBinaryTree(self, descriptions):\n children = set()\n m = {}\n for p,c,l in descriptions:\n np = m.setdefault(p, TreeNode(p))\n nc = m.setdefault(c, TreeNode(c))\n if l:\n np.left = nc\n else:\n np.right = nc\n children.add(c)\n root = (set(m) - set(children)).pop()\n return m[root]\n```\n
108,117
Create Binary Tree From Descriptions
create-binary-tree-from-descriptions
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, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid.
Array,Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node.
1,642
20
**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 createBinaryTree(int[][] descriptions) {\n Set<Integer> kids = new HashSet<>();\n Map<Integer, TreeNode> valToNode = new HashMap<>();\n for (int[] d : descriptions) {\n int parent = d[0], kid = d[1], left = d[2];\n valToNode.putIfAbsent(parent, new TreeNode(parent));\n valToNode.putIfAbsent(kid, new TreeNode(kid));\n kids.add(kid);\n if (left == 1) {\n valToNode.get(parent).left = valToNode.get(kid);\n }else {\n valToNode.get(parent).right = valToNode.get(kid);\n }\n }\n valToNode.keySet().removeAll(kids);\n return valToNode.values().iterator().next();\n }\n```\n```python\n def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n val_to_node, kids = {}, set()\n for parent, kid, left in descriptions:\n kids.add(kid)\n parent_node = val_to_node.setdefault(parent, TreeNode(parent))\n kid_node = val_to_node.setdefault(kid, TreeNode(kid))\n if left == 1:\n parent_node.left = kid_node\n else:\n parent_node.right = kid_node\n return val_to_node[(val_to_node.keys() - kids).pop()]\n```\n\n----\n\n**BFS**\n\n1. Build graph from parent to kids, and add parent and kids to `HashSet`s respectively;\n2. Remove all `kids` from `parents`, and the remaining is `root`;\n3. Starting from `root`, use BFS to construct binary tree according to the graph `parentsToKids` built in `1.`.\n\n```java\n public TreeNode createBinaryTree(int[][] descriptions) {\n Set<Integer> kids = new HashSet<>(), parents = new HashSet<>();\n Map<Integer, List<int[]>> parentToKids = new HashMap<>();\n for (int[] d : descriptions) {\n int parent = d[0], kid = d[1];\n parents.add(parent);\n kids.add(kid);\n parentToKids.computeIfAbsent(parent, l -> new ArrayList<>()).add(new int[]{kid, d[2]});\n }\n parents.removeAll(kids);\n TreeNode root = new TreeNode(parents.iterator().next());\n Deque<TreeNode> dq = new ArrayDeque<>();\n dq.offer(root);\n while (!dq.isEmpty()) {\n TreeNode parent = dq.poll();\n for (int[] kidInfo : parentToKids.getOrDefault(parent.val, Arrays.asList())) {\n int kid = kidInfo[0], left = kidInfo[1];\n dq.offer(new TreeNode(kid));\n if (left == 1) {\n parent.left = dq.peekLast();\n }else {\n parent.right = dq.peekLast();\n }\n }\n }\n return root;\n }\n```\n\n```python\n def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n g, kids, parents = defaultdict(list), set(), set()\n for parent, kid, left in descriptions:\n kids.add(kid)\n parents.add(parent)\n g[parent].append([kid, left])\n parents.difference_update(kids)\n root = TreeNode(parents.pop())\n dq = deque([root])\n while dq:\n parent = dq.popleft()\n for kid, left in g.pop(parent.val, []): \n dq.append(TreeNode(kid))\n if left == 1:\n parent.left = dq[-1]\n else:\n parent.right = dq[-1]\n return root\n```\n\n**Analysis:**\n\nEach node/value is visited at most twice, therefore,\n\nTime & space: `O(V + E)`, where `V = # of nodes, E = # of edges`.
108,121
Create Binary Tree From Descriptions
create-binary-tree-from-descriptions
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, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid.
Array,Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node.
727
10
**Structures used:**\n*map bank* : stores {int a, TreeNode* temp} pair, where *int a* is the node value, and *temp* is the address of the node with value same *int a*\n*set k* : cotains all the value of the nodes, and is used to find the root node\n\n**Explanation**\n* **Section 1** \n\tThe map *bank* and set *k* are populated here. If the node with value *des[i][0]* or *des[i][1]* (for all *i* from *0* to *des.size()-1*) have not been encountered before, then a TreeNode is made for them followed by making connections between them. \n\tThe set k is also inserted with various node value\n* **Section 2**\n\tOne key observation for finding the root is that, since root has no parents it will not occur as *des[i][1]* (for all *i* from *0* to *des.size()-1*). So I interate through the *des* vector again and pop all the *des[i][1]* so only one integer remains in set k at the begining position. and then return the TreeNode * associated to that root value using map bank\n\n```\nclass Solution {\npublic:\n TreeNode* createBinaryTree(vector<vector<int>>& des) \n {\n unordered_set<int> k; \n unordered_map<int, TreeNode*> bank;\n \n\t\t//Section 1\n\t\tfor(int i =0; i<des.size(); i++)\n {\n k.insert(des[i][0]);\n k.insert(des[i][1]);\n \n if(bank.find(des[i][0]) == bank.end())\n {\n TreeNode *temp = new TreeNode(des[i][0]);\n bank.insert({des[i][0], temp});\n }\n if(bank.find(des[i][1]) == bank.end())\n {\n TreeNode *temp = new TreeNode(des[i][1]);\n bank.insert({des[i][1], temp}); \n }\n \n if(des[i][2] == 0)\n bank[des[i][0]]->right = bank[des[i][1]];\n else\n bank[des[i][0]]->left = bank[des[i][1]];\n }\n \n\t\t//Section 2\n for(int i =0; i<des.size(); i++)\n k.erase(k.find(des[i][1]));\n \n return bank[*k.begin()];\n }\n};\n```
108,123
Create Binary Tree From Descriptions
create-binary-tree-from-descriptions
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, Construct the binary tree described by descriptions and return its root. The test cases will be generated such that the binary tree is valid.
Array,Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
Could you represent and store the descriptions more efficiently? Could you find the root node? The node that is not a child in any of the descriptions is the root node.
838
10
```\nclass Solution {\npublic:\n TreeNode* createBinaryTree(vector<vector<int>>& nums) {\n unordered_map<int,TreeNode*> hash;\n unordered_set<int> rootcomp;\n for(int i=0;i<nums.size();i++){\n if(!hash.count(nums[i][0])) hash[nums[i][0]]=new TreeNode(nums[i][0]);\n if(!hash.count(nums[i][1])) hash[nums[i][1]]=new TreeNode(nums[i][1]);\n rootcomp.insert(nums[i][1]);\n TreeNode* parent=hash[nums[i][0]]; TreeNode* child=hash[nums[i][1]];\n nums[i][2]==1?parent->left=child:parent->right=child;\n }\n for(int i=0;i<nums.size();i++) if(!rootcomp.count(nums[i][0])) return hash[nums[i][0]];\n return nullptr;\n }\n};\n```\n
108,124