title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
βŒ€
tag
stringclasses
643 values
level
stringclasses
3 values
question_hints
stringclasses
869 values
view_count
int64
19
630k
vote_count
int64
5
3.67k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
Maximum AND Sum of Array
maximum-and-sum-of-array
You are given an integer array nums of length n and an integer numSlots such that 2 * numSlots >= n. There are numSlots slots numbered from 1 to numSlots. You have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of every number with its respective slot number. Return the maximum possible AND sum of nums given numSlots slots.
Array,Dynamic Programming,Bit Manipulation,Bitmask
Hard
Can you think of a dynamic programming solution to this problem? Can you use a bitmask to represent the state of the slots?
13,194
165
Watching Beijing Olympics game,\nyou will be encouraged and have better performance on LeetCode.\n\n# **Intuition**\nDP solution, but need to figure out how to define bit mask.\n\nI considered two options\n1) Use a mask on base-3\n2) Use a mask on base-2, and each slot takes two bits.\n\nI feel no big difference on code length,\nand base-3 has slightly better complexity.\n<br>\n\n# **Optimization**\nUsually the bitmask dp will be in format of `dp(i, mask) = max(current, dp(i, mask - bit) + value)`\nand we memorized `dp(i, mask)`.\nActually in this problem, I only memorized `mask`, without caring about `i`.\nSince `mask` has the information of the `slots` used\n<br>\n\n# **Explanation**\nWe recursively check `dp(i, mask)`,\nmeanning we are going to assign `A[i]` with current bitmask `mask`.\n`dp(i, mask)` is the biggest AND sum we can get, by assign `A[0]` to `A[i]` into the remaining slots.\n\nWe iterate all slots, the corresponding `bit = 3 ** (slot - 1)`.\nTher check if this `slot` is availble.\nIf it\'s available, we take it and recursively check `dp(i - 1, mask - bit)`.\n<br>\n\n# **Complexity**\nTime `O(ns * 3^ns)`\nSpace `O(3^ns)`\n<br>\n\n**Java**\n```java\n public int maximumANDSum(int[] A, int ns) {\n int mask = (int)Math.pow(3, ns) - 1;\n int[] memo = new int[mask + 1];\n return dp(A.length - 1, mask, ns, memo, A);\n }\n \n private int dp(int i, int mask, int ns, int[] memo, int[] A) {\n if (memo[mask] > 0) return memo[mask];\n if (i < 0) return 0;\n for (int slot = 1, bit = 1; slot <= ns; ++slot, bit*= 3)\n if (mask / bit % 3 > 0)\n memo[mask] = Math.max(memo[mask], (A[i] & slot) + dp(i - 1, mask - bit, ns, memo, A));\n return memo[mask];\n }\n```\n\n**C++**\nUsing helper function\n```cpp\n int maximumANDSum(vector<int>& A, int ns) {\n int mask = pow(3, ns) - 1;\n vector<int> memo(mask + 1, 0);\n return dp(A.size() - 1, mask, ns, memo, A);\n }\n \n int dp(int i, int mask, int ns, vector<int>& memo, vector<int>& A) {\n if (memo[mask] > 0) return memo[mask];\n if (i < 0) return 0;\n for (int slot = 1, bit = 1; slot <= ns; ++slot, bit*= 3)\n if (mask / bit % 3 > 0)\n memo[mask] = max(memo[mask], (A[i] & slot) + dp(i - 1, mask - bit, ns, memo, A));\n return memo[mask];\n }\n```\n\n**C++**\nusing lambda function\n```cpp\n int maximumANDSum(vector<int>& A, int ns) {\n int mask = pow(3, ns) - 1;\n vector<int> memo(mask + 1, 0);\n\n function<int(int, int)> dp =\n [&](int i, int mask) {\n int& res = memo[mask];\n if (res > 0) return res;\n if (i < 0) return 0;\n for (int slot = 1, bit = 1; slot <= ns; ++slot, bit *= 3)\n if (mask / bit % 3 > 0)\n res = max(res, (A[i] & slot) + dp(i - 1, mask - bit));\n return res;\n };\n\n return dp(A.size() - 1, mask);\n }\n```\n**Python3**\n```py\n def maximumANDSum(self, A, ns):\n @lru_cache(None)\n def dp(i, mask):\n res = 0\n if i == len(A): return 0\n for slot in range(1, ns + 1):\n b = 3 ** (slot - 1)\n if mask // b % 3 > 0:\n res = max(res, (A[i] & slot) + dp(i + 1, mask - b))\n return res\n \n return dp(0, 3 ** ns - 1)\n```\n
107,561
Maximum AND Sum of Array
maximum-and-sum-of-array
You are given an integer array nums of length n and an integer numSlots such that 2 * numSlots >= n. There are numSlots slots numbered from 1 to numSlots. You have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of every number with its respective slot number. Return the maximum possible AND sum of nums given numSlots slots.
Array,Dynamic Programming,Bit Manipulation,Bitmask
Hard
Can you think of a dynamic programming solution to this problem? Can you use a bitmask to represent the state of the slots?
1,111
16
Please pull this [commit]() for solutions of weekly 280. \n\n```\nclass Solution:\n def maximumANDSum(self, nums: List[int], numSlots: int) -> int:\n \n @cache\n def fn(k, m): \n """Return max AND sum."""\n if k == len(nums): return 0 \n ans = 0 \n for i in range(numSlots): \n if m & 1<<2*i == 0 or m & 1<<2*i+1 == 0: \n if m & 1<<2*i == 0: mm = m ^ 1<<2*i\n else: mm = m ^ 1<<2*i+1\n ans = max(ans, (nums[k] & i+1) + fn(k+1, mm))\n return ans \n \n return fn(0, 0)\n```
107,576
Maximum AND Sum of Array
maximum-and-sum-of-array
You are given an integer array nums of length n and an integer numSlots such that 2 * numSlots >= n. There are numSlots slots numbered from 1 to numSlots. You have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of every number with its respective slot number. Return the maximum possible AND sum of nums given numSlots slots.
Array,Dynamic Programming,Bit Manipulation,Bitmask
Hard
Can you think of a dynamic programming solution to this problem? Can you use a bitmask to represent the state of the slots?
1,150
9
\nI start with thinking over some greedy algorithm since brute-force seems infeasible here (`< O(perm(15, 15))` ~= 2^40). Later I realize the brute-force can be memorized via bitmask.\n\n---\n\nFor every slot, it can holds either `0`, `1` or `2` numbers, totaling three states. We need `ceil(log2(3)) = 2` bitmasks to represent the three states of all slots.\n\n`dp(i, mask1, mask2)` indictes the maximum possible AND sum when placing numbers starting from `i` till the end with some slots already filled as represented by `mask1` and `mask2`.\n\nWe use simple bit operations to mimic the procedure of a [half adder]((electronics)#Half_adder).\n\n**Code:**\n\n```python\nfrom functools import lru_cache, cache\n\nclass Solution:\n def maximumANDSum(self, nums: List[int], numSlots: int) -> int:\n @cache\n def dp(i=0, m1=0, m2=0): # mask1, mask2\n if i == len(nums):\n return 0\n ans = 0\n for s in range(numSlots):\n if m2 & (1 << s) == 0: # i.e. 0b0?, implying the slot is not full \n if m1 & (1 << s) == 0: # 0b00 + 1 => 0b01\n nm1 = m1 | (1 << s); nm2 = m2\n else: # 0b01 + 1 => 0b10\n nm1 = m1 & ~(1 << s); nm2 = m2 | (1 << s)\n ans = max(ans, dp(i + 1, nm1, nm2) + ((s + 1) & nums[i])) # s + 1 is the actual slot no.\n return ans\n return dp()\n```\n\n**Time complexity**:\n\n`\u0398(n*3^m*m)`\n\nwhere `n = len(nums)` and `m=len(numSlots)`.
107,577
Maximum AND Sum of Array
maximum-and-sum-of-array
You are given an integer array nums of length n and an integer numSlots such that 2 * numSlots >= n. There are numSlots slots numbered from 1 to numSlots. You have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of every number with its respective slot number. Return the maximum possible AND sum of nums given numSlots slots.
Array,Dynamic Programming,Bit Manipulation,Bitmask
Hard
Can you think of a dynamic programming solution to this problem? Can you use a bitmask to represent the state of the slots?
601
5
```\nclass Solution:\n def maximumANDSum(self, nums: List[int], numSlots: int) -> int:\n self.nums, self.n = nums, len(nums)\n \n counts = [0 for _ in range(numSlots)]\n \n return self.dfs(0, tuple(counts))\n\n @cache\n def dfs(self, cur, counts):\n if cur == self.n:\n return 0\n \n res, counts = 0, list(counts)\n for i, count in enumerate(counts):\n if count == 2:\n continue\n else:\n counts[i] += 1\n\t\t\t\tres = max(res, (self.nums[cur] & (i + 1)) + self.dfs(cur + 1, tuple(counts)))\n counts[i] -= 1\n \n return res\n```
107,581
Counting Words With a Given Prefix
counting-words-with-a-given-prefix
You are given an array of strings words and a string pref. Return the number of strings in words that contain pref as a prefix. A prefix of a string s is any leading contiguous substring of s.
Array,String
Easy
Go through each word in words and increment the answer if pref is a prefix of the word.
1,601
15
**Python**\n\n```\ndef prefixCount(self, words: List[str], pref: str) -> int:\n\treturn sum([word.startswith(pref) for word in words])\n```\n\n**Like it ? please upvote !**
107,648
Counting Words With a Given Prefix
counting-words-with-a-given-prefix
You are given an array of strings words and a string pref. Return the number of strings in words that contain pref as a prefix. A prefix of a string s is any leading contiguous substring of s.
Array,String
Easy
Go through each word in words and increment the answer if pref is a prefix of the word.
904
7
\tclass Solution:\n\t\tdef prefixCount(self, words: List[str], pref: str) -> int:\n\t\t\tn = len(pref)\n\t\t\tcount = 0\n\t\t\tfor w in words:\n\t\t\t\tif w[:n] == pref:\n\t\t\t\t\tcount += 1\n\n\t\t\treturn count
107,650
Minimum Number of Steps to Make Two Strings Anagram II
minimum-number-of-steps-to-make-two-strings-anagram-ii
You are given two strings s and t. In one step, you can append any character to either s or t. Return the minimum number of steps to make s and t anagrams of each other. An anagram of a string is a string that contains the same characters with a different (or the same) ordering.
Hash Table,String,Counting
Medium
Notice that for anagrams, the order of the letters is irrelevant. For each letter, we can count its frequency in s and t. For each letter, its contribution to the answer is the absolute difference between its frequency in s and t.
3,288
43
* Count the number of characters in each string \n* Compare the counts for each character\n* If the counts of the characters don\'t match, add the difference of the counts to answer\n<iframe src="" frameBorder="0" width="600" height="200"></iframe>\n\nTime complexity: `O(len(s) + (len(t))`
107,672
Minimum Number of Steps to Make Two Strings Anagram II
minimum-number-of-steps-to-make-two-strings-anagram-ii
You are given two strings s and t. In one step, you can append any character to either s or t. Return the minimum number of steps to make s and t anagrams of each other. An anagram of a string is a string that contains the same characters with a different (or the same) ordering.
Hash Table,String,Counting
Medium
Notice that for anagrams, the order of the letters is irrelevant. For each letter, we can count its frequency in s and t. For each letter, its contribution to the answer is the absolute difference between its frequency in s and t.
620
6
Please pull this [commit]() for solutions of weekly 282. \n\n```\nclass Solution:\n def minSteps(self, s: str, t: str) -> int:\n fs, ft = Counter(s), Counter(t)\n return sum((fs-ft).values()) + sum((ft-fs).values())\n```
107,680
Minimum Number of Steps to Make Two Strings Anagram II
minimum-number-of-steps-to-make-two-strings-anagram-ii
You are given two strings s and t. In one step, you can append any character to either s or t. Return the minimum number of steps to make s and t anagrams of each other. An anagram of a string is a string that contains the same characters with a different (or the same) ordering.
Hash Table,String,Counting
Medium
Notice that for anagrams, the order of the letters is irrelevant. For each letter, we can count its frequency in s and t. For each letter, its contribution to the answer is the absolute difference between its frequency in s and t.
784
6
For some reason, I misread the description, and tried to solve another problem.\n\n**Python 3**\n```python\nclass Solution:\n def minSteps(self, s: str, t: str) -> int:\n cs, ct = Counter(s), Counter(t)\n return sum(cnt for ch, cnt in ((cs - ct) + (ct - cs)).items())\n```\n**C++**\n```cpp\nint minSteps(string s, string t) {\n int cnt[26] = {};\n for (char ch : s) \n ++cnt[ch - \'a\'];\n for (char ch : t) \n --cnt[ch - \'a\'];\n return accumulate(begin(cnt), end(cnt), 0, [](int sum, int n){ return sum + abs(n); });\n}\n```
107,688
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.
1,864
8
\uD83D\uDD34 Check out [LeetCode The Hard Way]() for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our [Discord Study Group]() for live discussion.\n\uD83D\uDFE2 Give a star on [Github Repository]() and upvote this post if you like it.\n\uD83D\uDD35 Check out [YouTube Channel]() if you are interested.\n\n---\n\nThis is a classic problem of finding the smallest integer given a bound under a monotonic function.\n\nWe can perform binary search on the time needed to finish the trips, and we check that if we are able to complete totalTrips within the given amount of time. There are two components to this solution:\n\n- Binary Searching the smallest amount of time\n- Checking if totalTrips can be completed given a time\n\n```cpp\nclass Solution {\npublic:\n long long minimumTime(vector<int>& time, int totalTrips) {\n long long l = 0;\n long long r = 1LL * time[0] * totalTrips;\n while (l < r) {\n long long m = l + (r - l) / 2, trips = 0;\n for (auto x : time) trips += (m / x);\n if (trips < totalTrips) l = m + 1;\n else r = m;\n }\n return l;\n }\n};\n```\n\n```py\nclass Solution:\n def minimumTime(self, time: List[int], totalTrips: int) -> int:\n l, r = 0, time[0] * totalTrips\n while l < r:\n m = (l + r) // 2\n if sum(m // t for t in time) < totalTrips:\n l = m + 1\n else:\n r = m\n return l\n```
107,710
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 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
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.
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.
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
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.
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
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
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.
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.
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
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.
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,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.
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
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.
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.
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.
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
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.
649
11
Code is self explanatory...\nI used hashmap to store node\'s value as key and node as value... so by using key I can access particular node at any time....\nI took nodes set which I pushed all node values in it...\nI took children set which I pushed all children values in it..\n\nIf a node in the nodes set is not present in children set... that means that node is not a children.. i.e, that node doesnt have any parent... so return that particular node as root....\n\n```\n\nclass Solution:\n def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n hashmap = {}\n nodes = set()\n children = set()\n for parent,child,isLeft in descriptions:\n nodes.add(parent)\n nodes.add(child)\n children.add(child)\n if parent not in hashmap:\n hashmap[parent] = TreeNode(parent)\n if child not in hashmap:\n hashmap[child] = TreeNode(child)\n if isLeft:\n hashmap[parent].left = hashmap[child]\n if not isLeft:\n hashmap[parent].right = hashmap[child]\n \n for node in nodes:\n if node not in children:\n return hashmap[node]\n\n\n\n```\n\n**PLEASE UPVOTE IF U LIKE IT :).. FEEL FREE TO ASK QUERIES**
108,125
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.
531
13
Please pull this [commit]() for solutions of weekly 283.\n\n```\nclass Solution:\n def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n mp = {}\n seen = set()\n for p, c, left in descriptions: \n if p not in mp: mp[p] = TreeNode(p)\n if c not in mp: mp[c] = TreeNode(c)\n if left: mp[p].left = mp[c]\n else: mp[p].right = mp[c]\n seen.add(c)\n for p, _, _ in descriptions: \n if p not in seen: return mp[p]\n```
108,135
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.
516
5
Here we use a HashMap to keep track of node values and their references along with the fact if that node has a parent or not. We develop the Binary Tree as we go along. Finally we check which node has no parent as that node is the root node.\n1. Maintain a hash map with the keys being node values and value being a list of its `REFERENCE` and a `HAS_PARENT` property which tells weather or not it has a parent or not (Represented by True if it has False if not)\n2. Traverse through the descriptions list.\n3. For every new node value found, add a new TreeNode into the list with its `HAS_PARENT` property being False.\n4. Now make the child node parents left/right child and update the `HAS_PARENT` property of child value in map to True.\n5. Now once the Binary Tree is made we traverse through the hash map to check which node still has no parent. This node is out root node.\n6. Return the root node.\n```\nclass Solution:\n def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n root = None\n table = {}\n for arr in descriptions:\n parent = arr[0]\n child = arr[1]\n isleft = arr[2]\n if table.get(parent, None) is None: # If key parent does not exist in table\n table[parent] = [TreeNode(parent), False]\n if table.get(child, None) is None: If key child does not exist in table\n table[child] = [TreeNode(child), False]\n table[child][1] = True # Since child is going to have a parent in the current iteration, set its has parent property to True\n if isleft == 1:\n table[parent][0].left = table[child][0]\n else:\n table[parent][0].right = table[child][0]\n\t\t# Now traverse the hashtable and check which node still has no parent\n for k, v in table.items():\n if not v[1]: # Has parent is False, so root is found.\n root = k\n\t\t\t\tbreak\n return table[root][0]\n```
108,138
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.
383
8
```\nclass Solution:\n def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n \n tree = dict()\n children = set()\n for parent, child, isLeft in descriptions:\n if parent not in tree : tree[parent] = TreeNode(parent)\n if child not in tree : tree[child] = TreeNode(child)\n \n if isLeft : tree[parent].left = tree[child]\n else : tree[parent].right = tree[child]\n \n children.add(child)\n \n for parent in tree:\n if parent not in children:\n return tree[parent]\n \n```
108,152
Replace Non-Coprime Numbers in Array
replace-non-coprime-numbers-in-array
You are given an array of integers nums. Perform the following steps: Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 108. Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y.
Array,Math,Stack,Number Theory
Hard
Notice that the order of merging two numbers into their LCM does not matter so we can greedily merge elements to its left if possible. If a new value is formed, we should recursively check if it can be merged with the value to its left. To simulate the merge efficiently, we can maintain a stack that stores processed elements. When we iterate through the array, we only compare with the top of the stack (which is the value to its left).
4,453
69
# **Explanation**\nFor each number `a` in input array `A`,\ncheck if it is coprime with the last number `b` in `res`.\nIf it\'s not coprime, then we can merge them by calculate `a * b / gcd(a, b)`.\nand check we can continue to do this process.\n\nUntil it\'s coprime with the last element in `res`,\nwe append `a` at the end of `res`.\n\nWe do this for all elements `a` in `A`, and return the final result.\n<br>\n\n# **Complexity**\nTime `O(nlogn)`\nSpace `O(n)`\n<br>\n\n**Java**\n```java\n public List<Integer> replaceNonCoprimes(int[] A) {\n LinkedList<Integer> res = new LinkedList();\n for (int a : A) {\n while (true) {\n int last = res.isEmpty() ? 1 : res.getLast();\n int x = gcd(last, a);\n if (x == 1) break; // co-prime\n a *= res.removeLast() / x;\n }\n res.add(a);\n }\n return res;\n }\n\n private int gcd(int a, int b) {\n return b > 0 ? gcd(b, a % b) : a;\n }\n```\n\n**C++**\n```cpp\n vector<int> replaceNonCoprimes(vector<int>& A) {\n vector<int> res;\n for (int a: A) { \n while (true) { \n int x = gcd(res.empty() ? 1 : res.back(), a);\n if (x == 1) break; // co-prime\n a *= res.back() / x;\n res.pop_back();\n }\n res.push_back(a);\n }\n return res;\n }\n```\n\n**Python3**\n```py\n def replaceNonCoprimes(self, A):\n res = []\n for a in A:\n while True:\n x = math.gcd(res[-1] if res else 1, a)\n if x == 1: break # co-prime\n a *= res.pop() // x\n res.append(a)\n return res\n```\n
108,161
Replace Non-Coprime Numbers in Array
replace-non-coprime-numbers-in-array
You are given an array of integers nums. Perform the following steps: Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result. The test cases are generated such that the values in the final array are less than or equal to 108. Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y.
Array,Math,Stack,Number Theory
Hard
Notice that the order of merging two numbers into their LCM does not matter so we can greedily merge elements to its left if possible. If a new value is formed, we should recursively check if it can be merged with the value to its left. To simulate the merge efficiently, we can maintain a stack that stores processed elements. When we iterate through the array, we only compare with the top of the stack (which is the value to its left).
776
10
## idea\n- we process the numbers from left to right, when processing a number, merge it to the left (with the already processed elements) until we can\'t.\n- maintain the processed elements by a stack.\n## code\n- C++\n```\nclass Solution {\npublic:\n vector<int> replaceNonCoprimes(vector<int>& nums) {\n vector<int> res;\n for (auto num : nums) {\n while (!res.empty() && gcd(res.back(), num) > 1) {\n num = lcm(res.back(), num);\n res.pop_back();\n }\n res.push_back(num);\n }\n return res;\n }\n};\n```\n- Python3\n```\nclass Solution:\n def replaceNonCoprimes(self, nums: List[int]) -> List[int]:\n res = []\n for num in nums:\n while res and gcd(res[-1], num) > 1:\n num = lcm(res[-1], num)\n res.pop()\n res.append(num)\n return res\n```\n- JavaScript (is there any built-in `gcd` or `lcm` in js?)\n```\nfunction gcd(a, b) {\n while (b > 0) {\n a %= b;\n [a, b] = [b, a];\n }\n return a;\n}\nfunction lcm(a, b) {\n return a / gcd(a, b) * b;\n}\n\nvar replaceNonCoprimes = function(nums) {\n let res = new Array();\n for (let num of nums) {\n while (res.length > 0 && gcd(res.at(-1), num) > 1) {\n num = lcm(res.at(-1), num);\n res.pop();\n }\n res.push(num);\n }\n return res;\n};\n```\n- Time Complexity\n\t- `O(n * log(1e8))` as we process each element once, and the complexity of both `gcd(a, b)` and `lcm(a, b)` are known to be `O(log(max(a, b)))`\n- Space Complexity\n\t- `O(n)` used by `res`.\n## Similar Problems\n- Although the concepts are not exactly the same, the code of this problem looks like those related to **monotonic stacks**\n- [LC 496 - Next Greater Element I]() (solve it in linear time)\n- [LC 503 - Next Greater Element II]()\n- [LC 739 - Daily Temperatures]()\n- [LC 402 - Remove K Digits]()\n- [LC 1944 - Number of Visible People in a Queue]()\n- [LC 84 - Largest Rectangle in Histogram]()\n- [LC 85 - Maximum Rectangle]()\n- [LC 1340 - Jump Game V]()
108,168
Divide Array Into Equal Pairs
divide-array-into-equal-pairs
You are given an integer array nums consisting of 2 * n integers. You need to divide nums into n pairs such that: Return true if nums can be divided into n pairs, otherwise return false.
Array,Hash Table,Bit Manipulation,Counting
Easy
For any number x in the range [1, 500], count the number of elements in nums whose values are equal to x. The elements with equal value can be divided completely into pairs if and only if their count is even.
5,339
41
**Method 1: Count and check parity**\n\n```java\n public boolean divideArray(int[] nums) {\n int[] cnt = new int[501];\n for (int n : nums)\n ++cnt[n];\n return IntStream.of(cnt).allMatch(n -> n % 2 == 0);\n }\n```\n\n```python\n def divideArray(self, nums: List[int]) -> bool:\n return all(v % 2 == 0 for v in Counter(nums).values())\n```\n\n---\n\n**Method 2: check parity by boolean array**\n\n```java\n public boolean divideArray(int[] nums) {\n boolean[] odd = new boolean[501];\n for (int n : nums)\n odd[n] = !odd[n];\n return Arrays.equals(odd, new boolean[501]);\n }\n```\n```python\n def divideArray(self, nums: List[int]) -> bool:\n odd = [False] * 501\n for n in nums:\n odd[n] = not odd[n]\n return not any(odd)\n```\n\n---\n\n**Method 3: HashSet** - credit to **@SunnyvaleCA**.\n\n```java\n public boolean divideArray(int[] nums) {\n Set<Integer> seen = new HashSet<>();\n for (int num : nums) {\n if (!seen.add(num)) {\n seen.remove(num);\n }\n }\n return seen.isEmpty();\n }\n```\n```python\n def divideArray(self, nums: List[int]) -> bool:\n seen = set()\n for num in nums:\n if num in seen:\n seen.discard(num)\n else:\n seen.add(num)\n return not seen\n```\nor simplify it to follows: - credit to **@stefan4trivia**\n\n```python\nclass stefan4trivia:\n def divideArray(self, nums: List[int], test_case_number = [0]) -> bool:\n seen = set()\n for n in nums:\n seen ^= {n}\n return not seen\n```\n\n**Analysis:**\n\nTime & space: `O(n)`.
108,216
Maximize Number of Subsequences in a String
maximize-number-of-subsequences-in-a-string
You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maximum number of times pattern can occur as a subsequence of the modified text. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
String,Greedy,Prefix Sum
Medium
Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer.
6,391
177
# **Intuition**\nIf we add `pattern[0]`, the best option is to add at the begin.\nIf we add `pattern[1]`, the best option is to add at the end.\n<br>\n\n# **Explanation**\nFirstly we\'ll try to find the number of subquence `pattern` in the current string `text`\nIterate every character `c` from input string `text`,\n`cnt1` means the count of character `pattern[0]`,\n`cnt2` means the count of character `pattern[1]`.\n\nIf `c == pattern[1]`, \nit can build up string pattern with every `pattern[0]` before it,\nso we update `res += cnt1` as well as `cnt2++`\n\nIf `c == pattern[0]`, \nwe simply increment `cnt1++`.\n\nThen we consider of adding one more character:\n\nIf we add `pattern[0]`,\nthe best option is to add at the begin,\n`res += cnt2`\n\nIf we add `pattern[1]`,\nthe best option is to add at the end,\n`res += cnt1`\n<br>\n\n# **Tip**\nUse two `if` in my solution,\nto handle the corner case where `pattern[0] == pattern[1]`.\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(1)`\n<br>\n\n**Java**\n```java\n public long maximumSubsequenceCount(String s, String pattern) {\n long res = 0, cnt1 = 0, cnt2 = 0;\n for (int i = 0; i < s.length(); ++i) { \n if (s.charAt(i) == pattern.charAt(1)) { \n res += cnt1; \n cnt2++;\n }\n if (s.charAt(i) == pattern.charAt(0)) { \n cnt1++;\n }\n }\n return res + Math.max(cnt1, cnt2);\n }\n```\n**C++**\n```cpp\n long long maximumSubsequenceCount(string text, string pattern) {\n long long res = 0, cnt1 = 0, cnt2 = 0;\n for (char& c: text) { \n if (c == pattern[1])\n res += cnt1, cnt2++;\n if (c == pattern[0])\n cnt1++;\n }\n return res + max(cnt1, cnt2);\n }\n```\n**Python**\n```py\n def maximumSubsequenceCount(self, text, pattern):\n res = cnt1 = cnt2 = 0\n for c in text:\n if c == pattern[1]:\n res += cnt1\n cnt2 += 1\n if c == pattern[0]:\n cnt1 += 1\n return res + max(cnt1, cnt2)\n```\n<br>\n\n**Follow-up**\nYou can add either character anywhere in text exactly **`K`** times. \nReturn the result.\n
108,259
Maximize Number of Subsequences in a String
maximize-number-of-subsequences-in-a-string
You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters. You can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text. Return the maximum number of times pattern can occur as a subsequence of the modified text. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
String,Greedy,Prefix Sum
Medium
Find the optimal position to add pattern[0] so that the number of subsequences is maximized. Similarly, find the optimal position to add pattern[1]. For each of the above cases, count the number of times the pattern occurs as a subsequence in text. The larger count is the required answer.
751
17
**The things we need to observe at the start:**\n\n* Only way to maximise the number of subsequence is to either add `pattern[0]` at the start of the given string or to add `pattern[1]` at end of the given string. \n* If we can calculate the number of subsequence in the given string, we can easily calculate the final ans. It would be `ans = num_of_subsequence + max(count(pattern[0]), count(pattern[1]))`. If you wonder why we are adding the count of two character, it is indeed what we discussed in the first point. Either adding pattern[0] at the start or pattern[1] at the end. \n\n**How to calculate the number_of_subsequence?**\n\nWe iterate through every character in the given string and keep track of `count(pattern[0])` and` count(pattern[1])`, Whenever we encounter` pattern[1]`, we know that the `count(pattern[0])` before that character is` number_of_subsequence` possible, so we add that to the total.\n\n**Example:** text = "aabb", pattern = "ab"\n\n**a**abb -> count_a = 1, count_b = 0, total = 0\na**a**bb -> count_a = 2, count_b = 0, total = 0\naa**b**b -> count_a = 2, count_b = 1, total = 2\naab**b** -> count_a = 2, count_b = 2, total = 4\n\n**Talking is cheap:**\n```\nclass Solution:\n def maximumSubsequenceCount(self, text: str, pattern: str) -> int:\n total = count_a = count_b = 0\n for c in text:\n if c == pattern[1]:\n total += count_a\n count_b += 1\n if c == pattern[0]:\n count_a += 1\n \n return total + max(count_a, count_b)\n```\n**Note:** \n\tWe must handle` c == pattern[1]` before` c == pattern[0]`, to overcome cases where `pattern[0] == pattern[1]`
108,263
Minimum Operations to Halve Array Sum
minimum-operations-to-halve-array-sum
You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half.
Array,Greedy,Heap (Priority Queue)
Medium
It is always optimal to halve the largest element. What data structure allows for an efficient query of the maximum element? Use a heap or priority queue to maintain the current elements.
4,089
32
* First find sum of array\n* Put all the elements in a Max heap or a priority queue such that popping the queue gives you the max element\n* `k` is current sum of halved elements\n* While sum of array - `k` > sum of array / 2, pop an element out of the `pq`, half it, add it to `k` and `pq`\n<iframe src="" frameBorder="0" width="620" height="310"></iframe>
108,318
Minimum Operations to Halve Array Sum
minimum-operations-to-halve-array-sum
You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half.
Array,Greedy,Heap (Priority Queue)
Medium
It is always optimal to halve the largest element. What data structure allows for an efficient query of the maximum element? Use a heap or priority queue to maintain the current elements.
1,520
18
**Q & A**\n*Q1:* Why in `PriorityQueue<Double> pq=new PriorityQueue<>((a,b)->b-a);` the lambda expression does not work with `double`?\n*A1:* Not very sure, but I guess it is because that in Java `Comparator` interface there is only one `int compare(T o1, T o2)` method, of which the return type is `int`. Please refer to [Java 8 Comparator]().\n\nYou can use `Math.signum` to convert `double` to `int` as follows:\n```java\n PriorityQueue<Double> pq = new PriorityQueue<Double>((a, b) -> (int)Math.signum(b - a));\n```\n\n\n*Q2:* `Math.signum()` returns only 3 values(double) i.e `1.0, -1.0, 0.0`. Then how exactly sorting is happening in above lambda expression `(a, b) -> (int)Math.signum(b - a)`?\n*A2:* The returning 3 values are enough for comparing `2` elements in the array.\n\n`Arrays.sort(Object[])` uses Tim sort. The sorting algorithms like Tim Sort, Merge Sort, Quick Sort, and Heap Sort, etc., are comparison (of `2` elements) based. Therefore, we only need to know the result of each comparison between `2` elements: `<`, `=`, `>`, which we can get conclusion from the returning values `-1.0`, `0.0`, `1.0`.\n\n\n*Q3:* How does this work?\n```java\nPriorityQueue pq = new PriorityQueue((a, b) -> b.compareTo(a));\n```\n*A3:* `compareTo` is the method in `Comparable` interface and you can refer to [Java 8 Comparable Interface]().\n\n`int compareTo(T o)`\n\n"Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.\n\n..."\n\n\n*Q4:* And when to use `(b-a)` and when to use `b.compareTo(a)` in lambda expressions?\n*A4:* I would choose `b.compareTo(a)` if `(b - a)` could cause overflow. e.g, `a` and `b` are both `int` or `long` and `a = Integer.MIN_VALUE or Long.MIN_VALUE`.\n\nHowever, in case of no overflow, either is good to use.\n\n**Correct me if I am wrong.**\n\n\n**End of Q & A**\n\n----\n\nAlways reduce current max value by half.\n\n1. Compute the `half` of the sum of the input `nums`;\n2. Put all `nums` into a PriorityQueue/heap by reverse order;\n3. Poll out and cut the current max value by half and add it back to PriorityQueue/ heap, deduct the `half` of the sum accordingly and increase the counter `ops` by 1;\n4. Repeat 3 till `half <= 0`, then return `ops`.\n```java\n public int halveArray(int[] nums) {\n PriorityQueue<Double> pq = new PriorityQueue<>(Comparator.reverseOrder()); \n double half = IntStream.of(nums).mapToLong(i -> i).sum() / 2d;\n for (int n : nums) {\n pq.offer((double)n);\n }\n int ops = 0;\n while (half > 0) {\n double d = pq.poll();\n d /= 2;\n half -= d;\n pq.offer(d);\n ++ops;\n }\n return ops;\n }\n```\n\n```python\n def halveArray(self, nums: List[int]) -> int:\n half, ops = sum(nums) / 2, 0\n heap = [-num for num in nums]\n heapify(heap)\n while half > 0:\n num = -heappop(heap)\n num /= 2.0\n half -= num\n heappush(heap, -num)\n ops += 1\n return ops\n```\n\n**Analysis:**\n\nTime: `O(nlogn)`, space: `O(n)`, where `n = nums.length`.
108,320
Minimum Operations to Halve Array Sum
minimum-operations-to-halve-array-sum
You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.) Return the minimum number of operations to reduce the sum of nums by at least half.
Array,Greedy,Heap (Priority Queue)
Medium
It is always optimal to halve the largest element. What data structure allows for an efficient query of the maximum element? Use a heap or priority queue to maintain the current elements.
1,233
12
**Intuition**\n* On observing example cases first idea is to use greedy approach use the maximum value to subtract, because that will help us to attin the goal faster.\n* for example, [5,19,8,1]\n* maximum is 19, so subtract its half, 19-19/2 = 9.5\n* Now array is [5, 9.5, 8, 1]\n* Now maximum is 9.5 so subtract its half, 9.5 - 9.5/2 = 4.75\n* Now array is [5, 4.5, 8, 1], maximum is 8, so now choose 8 and subtract its half\n* Now array is [5, 4, 4, 1]\n* Now as the sum of array becomes at least half of the initial sum so return number of steps\n\n **C++**\n```\nclass Solution {\npublic:\n int halveArray(vector<int>& nums) {\n\t\tpriority_queue<double> pq;\n double totalSum = 0;\n double requiredSum = 0;\n for(auto x: nums){\n totalSum += x;\n pq.push(x);\n }\n \n requiredSum = totalSum/2;\n int minOps = 0;\n while(totalSum > requiredSum){\n double currtop = pq.top();\n pq.pop();\n currtop = currtop/2;\n totalSum -= currtop;\n pq.push(currtop);\n minOps++;\n }\n return minOps;\n\t}\n}\n\t\t\n```\n\n**Python**\n```\nclass Solution:\n def halveArray(self, nums: List[int]) -> int:\n # Creating empty heap\n maxHeap = []\n heapify(maxHeap) # Creates minHeap \n \n totalSum = 0\n for i in nums:\n # Adding items to the heap using heappush\n # for maxHeap, function by multiplying them with -1\n heappush(maxHeap, -1*i) \n totalSum += i\n \n requiredSum = totalSum / 2\n minOps = 0\n \n while totalSum > requiredSum:\n x = -1*heappop(maxHeap) # Got negative value make it positive\n x /= 2\n totalSum -= x\n heappush(maxHeap, -1*x) \n minOps += 1\n \n return minOps\n```\n\n**Upvote if you like and comment if you have doubt**
108,321
Minimum White Tiles After Covering With Carpets
minimum-white-tiles-after-covering-with-carpets
You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another. Return the minimum number of white tiles still visible.
String,Dynamic Programming,Prefix Sum
Hard
Can you think of a DP solution? Let DP[i][j] denote the minimum number of white tiles still visible from indices i to floor.length-1 after covering with at most j carpets. The transition will be whether to put down the carpet at position i (if possible), or not.
6,135
109
# **Explanation**\n`dp[i][k]` means that,\nusing `k` tiles to cover the first `i` tiles\nthe minimum number of white tiles still visible.\n\n\nFor each tile `s[i]`, we heve two options,\nOne option is doing nothing, `jump` this tile,\n`jump = dp[i - 1][k] + int(s[i - 1])`\nThe other option is covering this tile\n`cover = dp[i - l][k - 1]`\n\nThen we take the minimum result of two options:\n`dp[i][k] = min(jump, cover)`\n\nFinally after explore all combination of `(i,k)`,\nwe return `dp[n][nc]`.\n<br>\n\n# **Complexity**\nTime `O(NC)`\nSpace `O(NC)`\nwhere `N = floor.length` and `C = numCarpets`.\nSpace can be optimized to `O(N)`.\n<br>\n\n**Java**\n```java\n public int minimumWhiteTiles(String s, int nc, int l) {\n int n = s.length(), dp[][] = new int[n + 1][nc + 1];\n for (int i = 1; i <= n; ++i) {\n for (int k = 0; k <= nc; ++k) {\n int jump = dp[i - 1][k] + s.charAt(i - 1) - \'0\';\n int cover = k > 0 ? dp[Math.max(i - l, 0)][k - 1] : 1000;\n dp[i][k] = Math.min(cover, jump);\n }\n }\n return dp[n][nc];\n }\n```\n\n**C++**\n```cpp\n int minimumWhiteTiles(string s, int nc, int l) {\n int n = s.size();\n vector<vector<int>> dp(n + 1, vector<int>(nc + 1));\n for (int i = 1; i <= n; ++i) {\n for (int k = 0; k <= nc; ++k) {\n int jump = dp[i - 1][k] + s[i - 1] - \'0\';\n int cover = k > 0 ? dp[max(i - l, 0)][k - 1] : 1000;\n dp[i][k] = min(cover, jump);\n }\n }\n return dp[n][nc];\n }\n```\n\n**Python3**\n```py\n def minimumWhiteTiles(self, A, k, l):\n\n @lru_cache(None)\n def dp(i, k):\n if i <= 0: return 0\n return min(int(A[i - 1]) + dp(i - 1, k), dp(i - l, k - 1) if k else 1000)\n \n return dp(len(A), k) \n```\n
108,359
Minimum White Tiles After Covering With Carpets
minimum-white-tiles-after-covering-with-carpets
You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor: You are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another. Return the minimum number of white tiles still visible.
String,Dynamic Programming,Prefix Sum
Hard
Can you think of a DP solution? Let DP[i][j] denote the minimum number of white tiles still visible from indices i to floor.length-1 after covering with at most j carpets. The transition will be whether to put down the carpet at position i (if possible), or not.
238
5
```\nclass Solution:\n def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n n = len(floor)\n if carpetLen*numCarpets >= n:\n return 0\n floorlist = []\n for i in floor:\n if i == \'1\':\n floorlist.append(1)\n else:\n floorlist.append(0)\n dp=[[0] * n for i in range(numCarpets)]\n \n for i in range(carpetLen, n):\n dp[0][i] = min(floorlist[i] + dp[0][i-1], sum(floorlist[:i - carpetLen + 1]))\n for j in range(1, numCarpets):\n for i in range(carpetLen * j, n):\n dp[j][i] = min(floorlist[i] + dp[j][i - 1], dp[j - 1][i - carpetLen])\n return dp[-1][-1]\n```
108,371
Most Frequent Number Following Key In an Array
most-frequent-number-following-key-in-an-array
You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums. For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that: Return the target with the maximum count. The test cases will be generated such that the target with maximum count is unique.
Array,Hash Table,Counting
Easy
Count the number of times each target value follows the key in the array. Choose the target with the maximum count and return it.
2,909
26
**Java**\n```java\n public int mostFrequent(int[] nums, int key) {\n Map<Integer, Integer> freq = new HashMap<>();\n int mostFreq = -1;\n for (int i = 0, n = nums.length, max = 0; i + 1 < n; ++i) {\n if (nums[i] == key) {\n int candidate = nums[i + 1];\n freq.put(candidate, 1 + freq.getOrDefault(candidate, 0));\n if (freq.get(candidate) > max) {\n max = freq.get(candidate);\n mostFreq = candidate;\n }\n }\n }\n return mostFreq;\n }\n```\nOr make the above simpler as follows:\n\n```java\n public int mostFrequent(int[] nums, int key) {\n Map<Integer, Integer> freq = new HashMap<>();\n int mostFreq = nums[0];\n for (int i = 0, n = nums.length; i + 1 < n; ++i) {\n if (nums[i] == key && \n freq.merge(nums[i + 1], 1, Integer::sum) > \n freq.get(mostFreq)) {\n mostFreq = nums[i + 1];\n }\n }\n return mostFreq;\n }\n```\n\n----\n\n**Python 3**\n\n```python\n def mostFrequent(self, nums: List[int], key: int) -> int:\n c = Counter()\n for i, n in enumerate(nums):\n if n == key and i + 1 < len(nums):\n c[nums[i + 1]] += 1\n return c.most_common(1)[0][0]\n```\n\nOne liner for fun: - credit to **@stefan4trivia**.\n\n```python\n def mostFrequent(self, nums: List[int], key: int) -> int:\n return statistics.mode(b for a, b in itertools.pairwise(nums) if a == key)\n```
108,415
Most Frequent Number Following Key In an Array
most-frequent-number-following-key-in-an-array
You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums. For every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that: Return the target with the maximum count. The test cases will be generated such that the target with maximum count is unique.
Array,Hash Table,Counting
Easy
Count the number of times each target value follows the key in the array. Choose the target with the maximum count and return it.
773
8
**Solution - Count by hand**:\n```\nclass Solution:\n def mostFrequent(self, nums, key):\n counts = {}\n \n for i in range(1,len(nums)):\n if nums[i-1]==key:\n if nums[i] not in counts: counts[nums[i]] = 1\n else: counts[nums[i]] += 1\n \n return max(counts, key=counts.get)\n```\n\n**Solution - Counter**:\n```\nclass Solution:\n def mostFrequent(self, nums, key):\n arr = [nums[i] for i in range(1,len(nums)) if nums[i-1]==key]\n c = Counter(arr)\n return max(c, key=c.get)\n```\n\n**One-Liner - Counter**:\n```\nclass Solution:\n def mostFrequent(self, nums, key):\n return max(c := Counter([nums[i] for i in range(1,len(nums)) if nums[i-1]==key]), key=c.get)\n```\n\n**One-Liner - Mode**:\n```\nclass Solution:\n def mostFrequent(self, nums, key):\n return mode(nums[i] for i in range(1,len(nums)) if nums[i-1]==key)\n```\n\n**One-Liner - Mode with Pairwise** (Credit: [stefan4trivia]()):\n```\nclass Solution:\n def mostFrequent(self, nums, key):\n return mode(b for a, b in pairwise(nums) if a == key)\n```
108,431
Count Hills and Valleys in an Array
count-hills-and-valleys-in-an-array
You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums.
Array
Easy
For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted.
2,979
56
We start by taking a for loop which goes from 1 to length of array -1.\nSince we cannot take 2 adjacent values such that nums[i] == nums[j]. \nSo, we update the current value to previous value which will help us in counting the next hill or valley. \n\nTime complexity = O(n)\nSpace complexity = O(1)\n\n```class Solution:\n def countHillValley(self, nums: List[int]) -> int:\n hillValley = 0\n for i in range(1, len(nums)-1):\n if nums[i] == nums[i+1]:\n nums[i] = nums[i-1]\n if nums[i] > nums[i-1] and nums[i] > nums[i+1]: #hill check\n hillValley += 1\n if nums[i] < nums[i-1] and nums[i] < nums[i+1]: #valley check\n hillValley += 1\n return hillValley\n```
108,465
Count Hills and Valleys in an Array
count-hills-and-valleys-in-an-array
You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j]. Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index. Return the number of hills and valleys in nums.
Array
Easy
For each index, could you find the closest non-equal neighbors? Ensure that adjacent indices that are part of the same hill or valley are not double-counted.
968
7
The idea of this problem is pretty simple, we wish to count the number of Valleys and Hills in the array.\nThe solution used in this problem is focused on simplicity and being easy to understand.\nThis is O(n) time complexity, and O(n) memory complexity.\n\n**Strategy:**\n\nSo, to find if a number is a hill or a valley, we need to see if the neighboring values that aren\'t the same are both an increase or decrease relative to this number.\n\nStep 1:\n\nMake sure that there are no neighboring nodes of the same values, so turning something like ``[6,7,7,7,8,8,9,2] -> [6,7,8,9,2]``.\n\nStep 2:\n\nLoop through the array starting at the 2nd index and up to the 2nd last index, and increase the return value if a nodes neighbors are both greater than or less than the node.\n\n**Solution:**\n\n**C++**\n\n```\nint countHillValley(vector<int>& ns) {\n //Step 1\n std::vector<int> nums;\n int l = ns[0];\n nums.push_back(l);\n for (int n : ns) {\n if (n != l) {\n nums.push_back(n);\n l = n;\n }\n }\n \n //Step 2.\n int ret = 0;\n for (int i = 1; i < nums.size() - 1; i++) {\n if (nums[i-1] < nums[i] == nums[i+1] < nums[i]) ret++;\n }\n return ret;\n}\n```\n\n**Python**\n\n```\ndef countHillValley(self, ns: List[int]) -> int:\n #Step 1\n nums = []\n l = ns[0]\n nums.append(l)\n for n in ns:\n if n != l:\n nums.append(n)\n l = n\n \n #Step 2\n ret = 0\n for i in range (1, len(nums) - 1):\n if ((nums[i-1] < nums[i]) == (nums[i+1] < nums[i])):\n ret += 1\n \n return ret\n```\n\n**Javascript**\n\n```\nvar countHillValley = function(ns) {\n //Step 1\n nums = [];\n let l = ns[0];\n nums.push(l);\n for (let i = 0; i < ns.length; i++) {\n n = ns[i];\n if (n != l) {\n l = n;\n nums.push(n);\n }\n }\n\n \n //Step 2\n let ret = 0;\n for (let i = 1; i < nums.length - 1; i++) {\n if (nums[i-1] < nums[i] == nums[i+1] < nums[i]) ret++;\n }\n \n return ret; \n};\n```\n
108,481
Count Collisions on a Road
count-collisions-on-a-road
There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road.
String,Stack
Medium
In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer?
6,300
124
**Similar Question :-** [ ]\n**C++ Solution**\n\n```\nclass Solution {\npublic:\n int countCollisions(string dir) {\n \n int res(0), n(size(dir)), i(0), carsFromRight(0);\n \n while (i < n and dir[i] == \'L\') i++; // skipping all the cars going to left from beginning as they will never collide\n \n for ( ; i<n; i++) {\n if (dir[i] == \'R\') carsFromRight++;\n else {\n // if dir[i] == \'S\' then there will be carsFromRight number of collission\n // if dir[i] == \'L\' then there will be carsFromRight+1 number of collision (one collision for the rightmost cars and carsFromRight collision for the cars coming from left)\n res += (dir[i] == \'S\') ? carsFromRight : carsFromRight+1;\n carsFromRight = 0;\n }\n }\n return res;\n }\n};\n```\n\n**Java Solution**\n\n```\nclass Solution {\n public int countCollisions(String dir) {\n \n int res = 0, n = dir.length(), i = 0, carsFromRight = 0;\n \n while (i < n && dir.charAt(i) == \'L\') i++;\n \n for ( ; i<n; i++) {\n if (dir.charAt(i) == \'R\') carsFromRight++;\n else {\n res += (dir.charAt(i) == \'S\') ? carsFromRight : carsFromRight+1;\n carsFromRight = 0;\n }\n }\n return res;\n }\n}\n```\n**Python Solution**\n```\nclass Solution:\n def countCollisions(self, directions: str) -> int:\n \n res, n, i, carsFromRight = 0, len(directions), 0, 0\n \n while i < n and directions[i] == \'L\':\n i+=1\n \n while i<n:\n if directions[i] == \'R\':\n carsFromRight+=1\n else:\n res += carsFromRight if directions[i] == \'S\' else carsFromRight+1;\n carsFromRight = 0\n i+=1\n \n return res\n```\n**Upvote if it helps :)**
108,513
Count Collisions on a Road
count-collisions-on-a-road
There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road.
String,Stack
Medium
In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer?
2,040
74
All the cars that move to the middle will eventually collide.... \n\n```\nclass Solution:\n def countCollisions(self, directions: str) -> int:\n return sum(d!=\'S\' for d in directions.lstrip(\'L\').rstrip(\'R\'))\n```
108,515
Count Collisions on a Road
count-collisions-on-a-road
There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road.
String,Stack
Medium
In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer?
1,099
13
We can transform this problem into whether go right or go left cars will stop and count the sum of stops. After transformation, we just need to check the situation of each go left and go right car individually.\n\nStarting from left->right,\n\nIf there is no car at the beginning go right or stop, then go left car after them will never stop.\nExample\nLLLLL -> No one car will stop\nIf there one car stop or go right at the beginning, then go left car after them is bound to stop\nExample\nLR | LLL -> After R, three L will stop there are **three** left car stop\nLS | LLL -> After S, three L will stop\n\n\nStarting from right->left,\nIf there is no car at the beginning go left or stop, then go right car after them will never stop.\nExample\nRRRRR -> No one car will stop\n\nIf there is one car stop or go left at the beginning, then go right car after them is bound to stop\nExample\nRRR | LR -> After L, three RRR will stop \nRRR | SR -> After S, three R will stop\n\nThen we check wether left car will stop by (left->right) and then check wether right car will stop by (right->left). The answer is the sum\n\n\n\n```\nclass Solution:\n def countCollisions(self, directions: str) -> int:\n ans = 0\n # At the beginning, leftest car can go without collide\n # At the beginning, rightest car can go without collide\n \n leftc = rightc = 0\n \n for c in directions:\n # if left side, no car stop or right answer + 0\n # if left side start to have car go right or stop\n # then cars after that are bound to be stopped so answer + 1\n if c == "L":\n ans += leftc\n else:\n leftc = 1\n \n for c in directions[::-1]:\n # if right side, no car stop or left answer + 0\n # if right side start to have car go left or stop\n # then cars after that are bound to be stopped so answer + 1\n if c == "R":\n ans += rightc\n else:\n rightc = 1\n \n return ans\n```
108,526
Count Collisions on a Road
count-collisions-on-a-road
There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road.
String,Stack
Medium
In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer?
300
5
```\n return len(directions.lstrip(\'L\').rstrip(\'R\').replace(\'S\',\'\'))\n ```\n\n**Update:**\nExcept for the Left Most cars going in left and Rightmost Cars going towards Right\nEvery Car will collide So Counting these by taking length after removing stay
108,539
Count Collisions on a Road
count-collisions-on-a-road
There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point. You are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed. The number of collisions can be calculated as follows: After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion. Return the total number of collisions that will happen on the road.
String,Stack
Medium
In what circumstances does a moving car not collide with another car? If we disregard the moving cars that do not collide with another car, what does each moving car contribute to the answer? Will stationary cars contribute towards the answer?
577
5
This question is similar to the [Asteroid Collision]() question.\n\nWe need a few variables:\n- has_stationary - determines if there stationary objects which will result in collisions\n- number of cars moving towards the right - when they hit a left/stationary car, they will result in collisions\n\n```py\nclass Solution:\n def countCollisions(self, directions: str) -> int:\n has_stationary, right, collisions = False, 0, 0\n for direction in directions:\n if direction == \'R\':\n\t\t\t # Just record number of right-moving cars. We will resolve them when we encounter a left-moving/stationary car.\n right += 1\n elif direction == \'L\' and (has_stationary or right > 0): \n\t\t\t # Left-moving cars which don\'t have any existing right-moving/stationary cars to their left can be ignored. They won\'t hit anything.\n\t\t\t\t# But if there are right-moving/stationary cars, it will result in collisions and we can resolve them.\n\t\t\t\t# We reset right to 0 because they have collided and will become stationary cars.\n collisions += 1 + right\n right = 0\n has_stationary = True\n elif direction == \'S\':\n\t\t\t # Resolve any right-moving cars and reset right to 0 because they are now stationary.\n collisions += right\n right = 0\n has_stationary = True\n return collisions\n```\n\nShorter solution (but less readable IMO)\n\n```\nclass Solution:\n def countCollisions(self, directions: str) -> int:\n has_stationary, right, collisions = False, 0, 0\n for direction in directions:\n if direction == \'R\':\n right += 1\n elif (direction == \'L\' and (has_stationary or right > 0)) or direction == \'S\':\n collisions += (1 if direction == \'L\' else 0) + right\n right = 0\n has_stationary = True\n return collisions\n```
108,553
Longest Substring of One Repeating Character
longest-substring-of-one-repeating-character
You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries. The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i]. Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed.
Array,String,Segment Tree,Ordered Set
Hard
Use a segment tree to perform fast point updates and range queries. We need each segment tree node to store the length of the longest substring of that segment consisting of only 1 repeating character. We will also have each segment tree node store the leftmost and rightmost character of the segment, the max length of a prefix substring consisting of only 1 repeating character, and the max length of a suffix substring consisting of only 1 repeating character. Use this information to properly merge the two segment tree nodes together.
1,436
13
Keep track of both substrings of one repeating character and their lengths in `SortedList`. We can then find the substring that covers the query index, the one to the left, and the one to the right in O(logn) time. The rest is just tedious bookkeeping of substring split and merge. One pitfall to avoid is that both `add` and `remove` change the index of the elements in `SortedList`, so I defer those calls until I am done with the index.\n\n```\nfrom sortedcontainers import SortedList\n\nclass Solution:\n def longestRepeating(self, s: str, queryCharacters: str, queryIndices: List[int]) -> List[int]:\n sl = SortedList()\n length = SortedList()\n curr = 0\n for char, it in itertools.groupby(s):\n c = sum(1 for _ in it)\n length.add(c)\n sl.add((curr, curr + c, char))\n curr += c\n ans = []\n for char, i in zip(queryCharacters, queryIndices):\n t = (i, math.inf, \'a\')\n index = sl.bisect_right(t) - 1\n to_remove = [sl[index]]\n to_add = []\n left, right, original_char = to_remove[0]\n if original_char != char:\n length.remove(right - left)\n if right - left > 1:\n if i == left:\n left += 1\n to_add.append((left, right, original_char))\n length.add(right - left)\n elif i == right - 1:\n right -= 1\n to_add.append((left, right, original_char))\n length.add(right - left)\n else:\n to_add.append((left, i, original_char))\n length.add(i - left)\n to_add.append((i + 1, right, original_char))\n length.add(right - (i + 1))\n \n l, r = i, i + 1\n if index - 1 >= 0 and sl[index - 1][1:3] == (i, char):\n l, old_r, _ = sl[index - 1]\n to_remove.append(sl[index - 1])\n length.remove(old_r - l)\n if index + 1 < len(sl) and sl[index + 1][0] == i + 1 and sl[index + 1][2] == char:\n old_l, r, old_length = sl[index + 1]\n to_remove.append(sl[index + 1])\n length.remove(r - old_l)\n length.add(r - l)\n sl.add((l, r, char))\n for t in to_remove:\n sl.remove(t)\n sl.update(to_add)\n # print(sl)\n # print(length)\n ans.append(length[-1])\n\n return ans\n```\nSadly, I finished this 5 min. after the contest \uD83D\uDE41
108,618
Find All K-Distant Indices in an Array
find-all-k-distant-indices-in-an-array
You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key. Return a list of all k-distant indices sorted in increasing order.
Array
Easy
For every occurrence of key in nums, find all indices within distance k from it. Use a hash table to remove duplicate indices.
1,467
6
The idea here is :\n- Store all the indices of elements in a queue whose value is equal to key\n- for every index in nums, there are 2 options:\n - check with the near index backside whose value = key and difference<=k\n - check with the near index in front whose value = k and difference<=k\n\nCode:\n```\nclass Solution:\n def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:\n lis=deque([])\n prev_popped=-1\n for i in range(len(nums)):\n if(nums[i]==key):\n lis.append(i)\n ans=[]\n for i in range(len(nums)):\n if(len(lis)>0 and lis[0]<i):\n prev_popped = lis.popleft()\n if(prev_popped!=-1 and (i-prev_popped) <=k):\n ans.append(i)\n elif(len(lis)>0 and (lis[0]-i)<=k):\n ans.append(i)\n return ans\n```
108,671
Find All K-Distant Indices in an Array
find-all-k-distant-indices-in-an-array
You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key. Return a list of all k-distant indices sorted in increasing order.
Array
Easy
For every occurrence of key in nums, find all indices within distance k from it. Use a hash table to remove duplicate indices.
829
8
```\nclass Solution:\n def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:\n ind_j = []\n for ind, elem in enumerate(nums):\n if elem == key:\n ind_j.append(ind)\n res = []\n for i in range(len(nums)):\n for j in ind_j:\n if abs(i - j) <= k:\n res.append(i)\n break\n return sorted(res)\n```
108,675
Minimum Bit Flips to Convert Number
minimum-bit-flips-to-convert-number
A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal.
Bit Manipulation
Easy
If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip.
4,015
29
Number of different bits is the required bits to flip, to make start and goal same.\nWe can efficiently calculate them using xor operation : \n\n**Java one liner :** \n```\npublic int minBitFlips(int start, int goal) {\n return Integer.bitCount(start^goal);\n}\n```\n\n\n**CPP one liner :**\n```\nint minBitFlips(int start, int goal) {\n return __builtin_popcount(start^goal);\n}\n```\n\n**Python one liner :**\n```\ndef minBitFlips(self, start: int, goal: int) -> int:\n return (start ^ goal).bit_count()\n```\n\n**Javascript one liner :**\n```\nvar minBitFlips = function(start, goal) {\n return (start^goal).toString(2).split("0").join("").length;\n};\n```
108,771
Minimum Bit Flips to Convert Number
minimum-bit-flips-to-convert-number
A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal.
Bit Manipulation
Easy
If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip.
1,451
17
# Divmod Remainder Approach:\n#### Time Complexity: O(log(min(s,g))) --> O(log(n)) \n#### Space Complexity: O(1)\n\nWe divide s and q by 2 until either s or g equals zero.\nDuring this process, if the remainder of either of them **do not** equal eachother, we increment the counter.\n\n***This process is similar to converting a decimal number to binary***\n\n**Example:** s=10 g=7\n\n| iterations | s (binary) | g (binary) | counter | explaination\n| - | --- | --- | --- | ---- |\n1| 1010 |0111|+1| The last digit of s and g are ***different***\n2| 0101 |0011|+0| The last digits are the **same** so we do nothing\n3| 0010 |0001|+1| The last digit of s and g are ***different***\n4| 0001 |0000|+1|The last digit of s and g are ***different***\n\n```Python []\nclass Solution:\n def minBitFlips(self, s: int, g: int) -> int:\n count = 0 \n while s or g:\n if s%2 != g%2: count+=1\n s, g = s//2, g//2\n return count\n```\n```Java []\nclass Solution {\n public int minBitFlips(int s, int g) {\n int count = 0;\n while(s > 0 || g > 0){\n if(s%2 != g%2) count++;\n s = s/2;\n g = g/2;\n }\n return count;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int minBitFlips(int s, int g) {\n int count = 0;\n while(s > 0 || g > 0){\n if(s%2 != g%2) count++;\n s = s/2;\n g = g/2;\n }\n return count;\n }\n};\n```\n```PsudoCode []\nfunction minBitFlips(integer s, integer g){\n\tinitilize counter integer to 0\n\tloop until s or g is equal to zero{\n\t\tif the s mod 2 and g mod 2 have the same remainder, increment counter\n\t\tdivide s and g by 2 every pass\n\t}\n\treturn counter\n}\n```\n\n# PLEASE UPVOTE IF THIS HELPED YOU :)\n
108,775
Minimum Bit Flips to Convert Number
minimum-bit-flips-to-convert-number
A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal.
Bit Manipulation
Easy
If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip.
1,402
7
The given question requires us to count the total number of flips we need to do inorder to make `start -> goal`.\nEx: \n7 - 0111\n10 - 1010\nHere, we only flip the bits which are different in both **start** and **goal**, i.e. `01` or `10`. And, what helps us to find if the bits are different? **XOR**. \nNow, we count these bits (i.e. different bits). And how do we calculate the number of `1\'s` in a number? `n & (n-1)` technique.\n\nSo, the number of flips required is **3**.\n\nTherefore, the solution is divided into two parts - identify the distinct bits in both numbers and then, count these bits.\n\nSolution:\n```python\nclass Solution(object):\n def minBitFlips(self, start, goal):\n res = start ^ goal\n cnt = 0\n while res:\n res &= res - 1\n cnt += 1\n return cnt\n```\n\n
108,787
Minimum Bit Flips to Convert Number
minimum-bit-flips-to-convert-number
A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal.
Bit Manipulation
Easy
If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip.
855
7
**Just xor so we get 1 at places where bits are different and then count those bits.**\n```\nclass Solution:\n def minBitFlips(self, start: int, goal: int) -> int:\n return (bin(start^goal).count("1"))\n```
108,789
Minimum Bit Flips to Convert Number
minimum-bit-flips-to-convert-number
A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0. Given two integers start and goal, return the minimum number of bit flips to convert start to goal.
Bit Manipulation
Easy
If the value of a bit in start and goal differ, then we need to flip that bit. Consider using the XOR operation to determine which bits need a bit flip.
674
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minBitFlips(self, start: int, goal: int) -> int:\n s=bin(start)[2:].zfill(50)\n g=bin(goal)[2:].zfill(50)\n count=0\n for i in range(50):\n if s[i]!=g[i]:\n count+=1\n return count\n```
108,806
Find Triangular Sum of an Array
find-triangular-sum-of-an-array
You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums.
Array,Math,Simulation,Combinatorics
Medium
Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step.
6,112
35
We can do a simulation for a O(n * n) solution, but it\'s not interesting. Instead, we will use a bit of math to look at more efficient solutions.\n\nEach number in the array contributes to the final sum a certain number of times. We can visualize how to figure out factors for each number using [Pascal\'s triangle]():\n\n![image]()\n\nFor test case `[1, 2, 3, 4, 5]`, we will get `1 * 1 + 2 * 4 + 3 * 6 + 4 * 4 + 5 * 1` = `1 + 8 + 18 + 16 + 5` = `48`, or `8` after modulo `10`.\n\nThe bottom row of Pascal\'s triangle are [binomial coefficients](), which can be computed as `nCr(n - 1, i)`. \n\n## Approach 1: comb\nUsing the built-in `comb` Python function to compute `nCr`.\n**Python 3**\n```python\nclass Solution:\n def triangularSum(self, nums: List[int]) -> int:\n return sum(n * comb(len(nums) - 1, i) for i, n in enumerate(nums)) % 10\n```\n\n## Approach 2: Iterative nCr\nThe `nCr` can be computed iteratively as `nCr(r + 1) = nCr(r) * (n - r) / (r + 1)`.\n**Python 3**\n```python\nclass Solution:\n def triangularSum(self, nums: List[int]) -> int:\n res, nCr, n = 0, 1, len(nums) - 1\n for r, num in enumerate(nums):\n res = (res + num * nCr) % 10\n nCr = nCr * (n - r) // (r + 1)\n return res\n```\n## Approach 3: Pascal Triangle\nThe approach 2 above won\'t work for C++ as `nCr` can get quite large. \n\n> We could use modular arithmetic with inverse modulo for the division. However, for modulus `10`, we need to put co-primes `5` and `2` out of brackets before computing the inverse modulo. Check out [this post]((n)-time-O(1)-space-Python-189-ms-C%2B%2B-22-ms-Java-4-ms) by [StefanPochmann]() to see how to do it.\n\nInstead, we can build the entire Pascal Triangle once (for array sizes 1..1000) and store it in a static array. From that point, we can compute the result for any array in O(n). The runtime of the code below is 12 ms.\n\n**C++**\nNote that here we populate the Pascal Triangle lazilly. \n```cpp\nint c[1001][1001] = {}, n = 1;\nclass Solution {\npublic:\nint triangularSum(vector<int>& nums) {\n for (; n <= nums.size(); ++n) // compute once for all test cases.\n for (int r = 0; r < n; ++r) \n c[n][r] = r == 0 ? 1 : (c[n - 1][r - 1] + c[n - 1][r]) % 10;\n return inner_product(begin(nums), end(nums), begin(c[nums.size()]), 0) % 10;\n}\n};\n```
108,823
Find Triangular Sum of an Array
find-triangular-sum-of-an-array
You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums.
Array,Math,Simulation,Combinatorics
Medium
Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step.
210
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def triangularSum(self, nums: List[int]) -> int:\n n=len(nums)\n while n>0:\n for i in range(n-1):\n nums[i]=(nums[i]+nums[i+1])%10\n n-=1\n return nums[0]\n```
108,839
Find Triangular Sum of an Array
find-triangular-sum-of-an-array
You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums.
Array,Math,Simulation,Combinatorics
Medium
Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step.
2,948
22
```java\n public int triangularSum(int[] nums) {\n for (int n = nums.length; n > 0; --n) {\n for (int i = 1; i < n; ++i) {\n nums[i - 1] += nums[i];\n nums[i - 1] %= 10;\n }\n }\n return nums[0];\n }\n```\n```python\n def triangularSum(self, nums: List[int]) -> int:\n for j in range(len(nums), 0, -1):\n for i in range(1, j):\n nums[i - 1] += nums[i]\n nums[i - 1] %= 10\n return nums[0]\n```\n**Analysis:**\n\nTime: `O(n ^ 2)`, extra space: `O(1)`, where `n = nums.length`.
108,844
Find Triangular Sum of an Array
find-triangular-sum-of-an-array
You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums.
Array,Math,Simulation,Combinatorics
Medium
Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step.
1,548
8
# Approach\nGoals: return the single element of triangular sum\n\n![image]()\n\n\nWe can see from the image that we will sum up the first cell and the second cell. Then, since it\'s triangular, the length of the top row is greater (+1) than the next row. \n\n## Brute Force\n\n```python\nclass Solution:\n def triangularSum(self, nums: List[int]) -> int:\n n = len(nums)\n\n if n == 0: return 0\n if n == 1: return nums[0]\n\n prev = list(nums)\n while n > 1:\n cur = [0]*(n-1)\n for i in range(1, len(prev)):\n cur[i-1] = (prev[i] + prev[i-1]) % 10\n prev = cur\n n -= 1\n return cur[n//2]\n```\n\n## Optimal\n\n```python\nclass Solution:\n def triangularSum(self, nums: List[int]) -> int:\n n = len(nums)\n while n > 0:\n for i in range(n-1):\n nums[i] = (nums[i] + nums[i+1]) % 10\n n -= 1\n return nums[0]\n```
108,849
Find Triangular Sum of an Array
find-triangular-sum-of-an-array
You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive). The triangular sum of nums is the value of the only element present in nums after the following process terminates: Return the triangular sum of nums.
Array,Math,Simulation,Combinatorics
Medium
Try simulating the entire process. To reduce space, use a temporary array to update nums in every step instead of creating a new array at each step.
596
5
```\nclass Solution:\n def helper(self, nums: List[int]) -> List[int]:\n dp = []\n i = 0\n while i < len(nums) - 1:\n dp.append((nums[i] + nums[i + 1]) % 10)\n i += 1\n return dp\n \n def triangularSum(self, nums: List[int]) -> int:\n while len(nums) > 1:\n nums = self.helper(nums)\n return nums[0]\n```
108,856
Number of Ways to Select Buildings
number-of-ways-to-select-buildings
You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings.
String,Dynamic Programming,Prefix Sum
Medium
There are only 2 valid patterns: β€˜101’ and β€˜010’. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β€˜01’ or β€˜10’ first. Let n01[i] be the number of β€˜01’ subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β€˜0’s and β€˜1’s that exists in the prefix of s up to i respectively. Then n01[i] = n01[i – 1] if s[i] == β€˜0’, otherwise n01[i] = n01[i – 1] + n0[i – 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β€˜101’ and β€˜010β€˜ subsequences.
4,737
131
Traverse the input `s`:\n1. If encontering `0`, count subsequences ending at current `0`: `0`, `10` and `010`\'s; The number of `10` depends on how many `1`s before current `0`, and the number of `010` depends on how many `01` before current `0`;\n\nSimilarly, \n\n2. If encontering `1`, count subsequences ending at current `1`: `1`, `01` and `101`\'s; The number of `01` depends on how many `0`s before current `1`, and the number of `101` depends on how many `10` before current `1`.\n\n```java\n public long numberOfWays(String s) {\n long one = 0, zero = 0, oneZero = 0, zeroOne = 0, ways = 0;\n for (int i = 0; i < s.length(); ++i) {\n if (s.charAt(i) == \'0\') {\n ++zero;\n oneZero += one; // Count in \'10\'.\n ways += zeroOne; // Count in \'010\'.\n }else {\n ++one;\n zeroOne += zero; // Count in \'01\'.\n ways += oneZero; // Count in \'101\'.\n }\n }\n return ways;\n }\n```\n```python\n def numberOfWays(self, s: str) -> int:\n ways = 0\n one = zero = zero_one = one_zero = 0\n for c in s:\n if c == \'0\':\n zero += 1\n one_zero += one\n ways += zero_one\n else:\n one += 1 \n zero_one += zero \n ways += one_zero\n return ways\n```\n\n**Analysis:**\n\nTime: `O(n)`, space: `O(1)`, where `n = s.length()`.\n\n----\n\n**Follow-up**\nWhat if the city official would like to select `k`, instead of `3`, buildings?\n\n~~~If **the upvotes can reach `25`**, I will provide time `O(k * n)` space `O(k)` code for the follow-up.~~~\n\nTraverse the input `s`:\n1. If encontering `0`, count subsequences ending at current `0`: `0`, `10` and `010`, `1010`\'s, ...,; The number of `10` depends on how many `1`s before current `0`, the number of `010` depends on how many `01` before current `0`, and the number of `1010` depends on how many `101` before current `0`...;\n\nSimilarly,\n\n2. If encontering `1`, count subsequences ending at current `1`: `1`, `01`, `101`, and `0101`\'s; The number of `01` depends on how many `0`s before current `1`, the number of `101` depends on how many `10` before current `1`, and the number of `0101` depends on how many `010` before current `1`...\n3. We can observe the above patterns and use a 2-D array `ways` to record the corresponding subsequences, e.g., \n \n\t ways[0][0] - number of `0`\'s;\n\t ways[1][0] - number of `10`\'s;\n\t ways[2][0] - number of `010`\'s;\n\t ways[3][0] - number of `1010`\'s;\n\t ...\n\t ways[0][1] - number of `1`\'s;\n\t ways[1][1] - number of `01`\'s;\n\t ways[2][1] - number of `101`\'s;\n\t ways[3][1] - number of `0101`\'s;\n\t ...\n\t \n```java\n public long numberOfWays(String s, int k) {\n // int k = 3;\n long[][] ways = new long[k][2]; \n for (int i = 0; i < s.length(); ++i) {\n int idx = s.charAt(i) - \'0\';\n ++ways[0][idx];\n for (int j = 1; j < k; ++j) {\n ways[j][idx] += ways[j - 1][1 - idx];\n }\n }\n return ways[k - 1][0] + ways[k - 1][1];\n }\n```\n```python\n def numberOfWays(self, s: str, k: int) -> int:\n # k = 3\n ways = [[0, 0] for _ in range(k)]\n for c in s:\n idx = ord(c) - ord(\'0\')\n ways[0][idx] += 1\n for i in range(1, k):\n ways[i][idx] += ways[i - 1][1 - idx]\n return sum(ways[-1])\n```\n**Analysis:**\n\nTime: `O(k * n)`, space: `O(k)`, where `n = s.length()`.\n\n**Do let me know** if you have an algorithm better than `O(k * n)` time or `O(k)` space for the follow-up.
108,865
Number of Ways to Select Buildings
number-of-ways-to-select-buildings
You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings.
String,Dynamic Programming,Prefix Sum
Medium
There are only 2 valid patterns: β€˜101’ and β€˜010’. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β€˜01’ or β€˜10’ first. Let n01[i] be the number of β€˜01’ subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β€˜0’s and β€˜1’s that exists in the prefix of s up to i respectively. Then n01[i] = n01[i – 1] if s[i] == β€˜0’, otherwise n01[i] = n01[i – 1] + n0[i – 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β€˜101’ and β€˜010β€˜ subsequences.
1,675
24
In overall, they are only looking for \'101\' and \'010\'.\nWe keep track of previous \'0\' and \'1\' using variable \'z\' and \'o\'.\nWhen entering the next building, the previous \'0\' and \'1\' can be upgraded into \'01\' and \'10\' respectively as variable \'oz\' and \'zo\'.\nAgain, from the previous \'01\' and \'10\', we can upgrade them into \'010\' and \'101\' and put them both into variable \'total\', which will be the total valid ways to select 3 buildings.\n```\ndef sumScores(self, s):\n\t# Idea 1: count 0, 1, 01, 10\n z, o, zo, oz, total = 0, 0, 0, 0, 0\n for c in s:\n if c == \'1\':\n total += oz\n zo += z\n o += 1\n elif c == \'0\':\n total += zo\n oz += o\n z += 1\n return total\n
108,869
Number of Ways to Select Buildings
number-of-ways-to-select-buildings
You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings.
String,Dynamic Programming,Prefix Sum
Medium
There are only 2 valid patterns: β€˜101’ and β€˜010’. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β€˜01’ or β€˜10’ first. Let n01[i] be the number of β€˜01’ subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β€˜0’s and β€˜1’s that exists in the prefix of s up to i respectively. Then n01[i] = n01[i – 1] if s[i] == β€˜0’, otherwise n01[i] = n01[i – 1] + n0[i – 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β€˜101’ and β€˜010β€˜ subsequences.
546
8
```\ndef numberOfWays(self, s: str) -> int:\n ways = one = zero = onesAfterZero = zerosAfterOne = 0\n\t\tfor i in s:\n\t\t\tif i == \'0\':\n\t\t\t\tzero += 1\n\t\t\t\tzerosAfterOne += one\n\t\t\t\tways += onesAfterZero\n\t\t\telse:\n\t\t\t\tone += 1\n\t\t\t\tonesAfterZero += zero\n\t\t\t\tways += zerosAfterOne\n\t\treturn ways\n```
108,892
Number of Ways to Select Buildings
number-of-ways-to-select-buildings
You are given a 0-indexed binary string s which represents the types of buildings along a street where: As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type. Return the number of valid ways to select 3 buildings.
String,Dynamic Programming,Prefix Sum
Medium
There are only 2 valid patterns: β€˜101’ and β€˜010’. Think about how we can construct these 2 patterns from smaller patterns. Count the number of subsequences of the form β€˜01’ or β€˜10’ first. Let n01[i] be the number of β€˜01’ subsequences that exist in the prefix of s up to the ith building. How can you compute n01[i]? Let n0[i] and n1[i] be the number of β€˜0’s and β€˜1’s that exists in the prefix of s up to i respectively. Then n01[i] = n01[i – 1] if s[i] == β€˜0’, otherwise n01[i] = n01[i – 1] + n0[i – 1]. The same logic applies to building the n10 array and subsequently the n101 and n010 arrays for the number of β€˜101’ and β€˜010β€˜ subsequences.
1,334
10
```\nclass Solution:\n def numberOfWays(self, s: str) -> int:\n \n temp = []\n c0 = 0\n c1 = 0\n for char in s :\n if char == "0" :\n c0+=1\n else:\n c1+=1\n temp.append([c0,c1])\n \n total0 = c0\n total1 = c1\n \n \n count = 0\n for i in range(1, len(s)-1) :\n \n if s[i] == "0" :\n m1 = temp[i-1][1]\n m2 = total1 - temp[i][1]\n count += m1*m2\n \n else:\n m1 = temp[i-1][0]\n m2 = total0 - temp[i][0]\n count += m1*m2\n return count\n \n \n```
108,900
Largest Number After Digit Swaps by Parity
largest-number-after-digit-swaps-by-parity
You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). Return the largest possible value of num after any number of swaps.
Sorting,Heap (Priority Queue)
Easy
The bigger digit should appear first (more to the left) because it contributes more to the value of the number. Get all the even digits, as well as odd digits. Sort them separately. Reconstruct the number by giving the earlier digits the highest available digit of the same parity.
3,952
25
Since we need the largest number, what we want is basically to have the larger digits upfront and then the smaller ones. But we are given a parity condition that we need to comply to. We are allowed to swap odd digits with odd ones and even with even ones. So we simply maintain two arrays with odd and even digits. The we construct out answer by taking values from the odd or even arrays as per the parity of ith index. \n\n**STEPS**\n1. First make a array with the digits from nums.\n2. Then we traverse through the array and insert odd and even values into `odd` and `even` lists.\n3. We sort these `odd` and `even` lists.\n4. Then traverse from 0 to n, at each step we check for the parity at that index. For even parity we take the largest value from even array and for odd parity we take from odd array. **WE TAKE THE LARGEST VALUE AS A GREEDY CHOICE TO MAKE THE RESULTING NUMBER LARGER.**\n5. Return the result.\n\n**CODE**\n```\nclass Solution:\n def largestInteger(self, num: int):\n n = len(str(num))\n arr = [int(i) for i in str(num)]\n odd, even = [], []\n for i in arr:\n if i % 2 == 0:\n even.append(i)\n else:\n odd.append(i)\n odd.sort()\n even.sort()\n res = 0\n for i in range(n):\n if arr[i] % 2 == 0:\n res = res*10 + even.pop()\n else:\n res = res*10 + odd.pop()\n return res\n```
108,978
Minimize Result by Adding Parentheses to Expression
minimize-result-by-adding-parentheses-to-expression
You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'. Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
String,Enumeration
Medium
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
2,609
16
*Since the given maximum size is only 10, we can easily cover all possible options without TLE. Thus we use 2 pointers to cover all options.*\n\n**STEPS**\n1. Traverse two pointers `l` & `r`. **L** pointer goes from 0 to **plus_index** and **R** pointer goes from **plus_index+1** to **N**. **plus_index** is the index of \'+\' in the expression. The **L** pointer is the position of \'(\' and **R** is for \')\'.\n2. Use f string formatting to generate a expression. \n3. Use evaulate function to get the result of the following expression.\n4. If the new result is better than the old one, then update otherwise continue.\n \n**NOTE** \n\u27A1\uFE0F**The `evaluate` function basically converts "23(44+91)2" into "23 X (44+91) X 2" without ever having any * sign in the edges(used strip methods for that). `eval()` is a library function that evaluates a mathematical expression given in string form.**\n\u27A1\uFE0F **`ans` is a list of 2 values, first is the smalles result of any expression and second is the expression itself.**\n\n**CODE**\n```\nclass Solution:\n def minimizeResult(self, expression: str) -> str:\n plus_index, n, ans = expression.find(\'+\'), len(expression), [float(inf),expression] \n def evaluate(exps: str):\n return eval(exps.replace(\'(\',\'*(\').replace(\')\', \')*\').lstrip(\'*\').rstrip(\'*\'))\n for l in range(plus_index):\n for r in range(plus_index+1, n):\n exps = f\'{expression[:l]}({expression[l:plus_index]}+{expression[plus_index+1:r+1]}){expression[r+1:n]}\'\n res = evaluate(exps)\n if ans[0] > res:\n ans[0], ans[1] = res, exps\n return ans[1]\n```
109,019
Minimize Result by Adding Parentheses to Expression
minimize-result-by-adding-parentheses-to-expression
You are given a 0-indexed string expression of the form "<num1>+<num2>" where <num1> and <num2> represent positive integers. Add a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'. Return expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them. The input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
String,Enumeration
Medium
The maximum length of expression is very low. We can try every possible spot to place the parentheses. Every possibility of expression is of the form a * (b + c) * d where a, b, c, d represent integers. Note the edge cases where a and/or d do not exist, in which case use 1 instead of them.
1,270
5
```\nclass Solution:\n def minimizeResult(self, expression: str) -> str: # Example: "247+38" \n # left, right = "247","38"\n left, right = expression.split(\'+\') \n value = lambda s:eval(s.replace(\'(\',\'*(\').replace(\')\',\')*\').strip(\'*\')) \n \n lft = [ left[0:i]+\'(\'+ left[i:] for i in range( len(left ) )] # lft = [\'(247\', \'2(47\', \'24(7\']\n rgt = [right[0:i]+\')\'+right[i:] for i in range(1,len(right)+1)] # rgt = [\'3)8\', \'38)\']\n \n return min([l+\'+\'+r for l in lft for r in rgt], key = value) # = min[(247+3)8,(247+38),2(47+3)8,2(47+38),24(7+3)8,24(7+38)]\n # | | | | | | \n # 2000 285 800 170 1920 1080 \n # |\n # return 2(47+38)\n\n```\n[](http://)\n\nI could be wrong, but I think time complexity is *O*(*N*^2) and space complexity is *O*(*N*).
109,022
Maximum Product After K Increments
maximum-product-after-k-increments
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Array,Greedy,Heap (Priority Queue)
Medium
If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.
84
7
\uD83D\uDCAF\uD83D\uDD25 C++ | Java || Python || JavaScript \uD83D\uDCAF\uD83D\uDD25\n\n***Read Whole article :*** \n\nVideo : \n\nAppraoch : min Heap / priority queue\n\nViuslizationn\n![image]()\n\n![image]()\n\n\n***Read Whole article :***
109,059
Maximum Product After K Increments
maximum-product-after-k-increments
You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1. Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo.
Array,Greedy,Heap (Priority Queue)
Medium
If you can increment only once, which number should you increment? We should always prioritize the smallest number. What kind of data structure could we use? Use a min heap to hold all the numbers. Each time we do an operation, replace the top of the heap x by x + 1.
2,095
18
```\nimport heapq\n\nclass Solution:\n def maximumProduct(self, nums, k: int) -> int:\n \n # creating a heap\n heap = []\n for i in nums:\n heapq.heappush (heap,i)\n \n \n # basic idea here is keep on incrementing smallest number, then only multiplication of that number will be greater\n # so basically till I have operations left I will increment my smallest number\n while k :\n current = heapq.heappop(heap)\n heapq.heappush(heap, current+1)\n k-=1\n \n result =1\n \n # Just Multiply all the numbers in heap and return the value\n while len(heap)>0:\n x= heapq.heappop(heap)\n result =(result*x )% (10**9+7)\n \n return result\n```
109,068
Maximum Total Beauty of the Gardens
maximum-total-beauty-of-the-gardens
Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens. You are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers, which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target, full, and partial. A garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following: Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.
Array,Two Pointers,Binary Search,Greedy,Sorting
Hard
Say we choose k gardens to be complete, is there an optimal way of choosing which gardens to plant more flowers to achieve this? For a given k, we should greedily fill-up the k gardens with the most flowers planted already. This gives us the most remaining flowers to fill up the other gardens. After sorting flowers, we can thus try every possible k and what is left is to find the highest minimum flowers we can obtain by planting the remaining flowers in the other gardens. To find the highest minimum in the other gardens, we can use binary search to find the most optimal way of planting.
2,474
17
First, sort the `flowers` list in ascending order. If we want to make some gardens full, we should choose those with more planted flowers to "fulfill".\n\nAssume that we want to get scores by making the largest `k` gardens full, while the rest `n-k` gardens have a max-min value of `flowers`. We need to sum up all missing values of the largest `k` flowers `sum[(max(0,target-flower) for flower in flowers[:-k]]`, which can be optimized by a "reversed" prefix sum array (for *prefix sum*, see [LC 303]()) in a O(n) time. Here, I use `lack[k]` to accumulate the total flowers required to make the largest `k` `flower` full. (**Note**: In some corner cases, all gardens are already full before planting new flowers, as we can\'t remove any planted flowers. Thus, we should start `k` with the min one that lets `lack[i]`>0 to avoid handling some full gardens as *incomplete* ones.)\n\nAfter fulfilling `k` gardens, the rest `n-k` gardens can be planted with **at most** `newFlowers-lack[k]` flowers. We\'re just curious about what is the max min value when adding `newFlowers-lack[k]` to `flowers[:n-k]`. This question satisfies the property of *binary-search* with a lower bound as `flowers[0]` (the origin min value) and an upper bound as `target` (**Note**: *In fact, after adding all `newFlowers-lack[k]`, the min value of `flowers[:n-k]` may >= `target`. However, we don\'t want to account for this case here because it will be considered later when we increase `k` to `n`, so the upper bound is limited to `target-1` inclusively*), so the score from the remaining `n-k` incomplete gardens can be obtained in `O(log(target)*cost(condition))`, in which `cost(condition)` denotes the time cost to check if the current min-value `flower` can be achieved by adding `newFlowers-lack[k]` flowers.\n \nTraditionally, finding the max-min value of an array after adding some numbers is a typical **load balancer problem**, which is similar to Q3 this week and the first challenge problem hosted by Amazon Last Mile Delivery last week. But the traditional linear way to calculate the max-min value is of time complexity in `O(n)` even with the auxiliary of the pre-sum array, which leads to a TLE in the contest. To reduce the runtime, we just need to check if a min `flower` can be achieved after adding `f` new flowers to the first `k` gardens *optimally*, here I use `fill(flower, f, k)` as a conditional checker to determine if it is feasible to all first `k` gardens are of >= `flower` flowers. Given the `fill` function, we can quickly apply the [binary search template]() to finish the skeleton of getting the actual max-min of `flower[:k]`.\n\nNow, let\'s look into `fill(flower, f, k)`: we check how many elements < `flower` there by binary-search as well, we call it `m`. Then, we try to make up the total diff values between those elements and our required `flower`, so we just need to check if the sum of the first `m` elements >= `m*flower` after adding `m` to the left-hand of the inequity, which can be easily solved when we have already known the sum of first `m` elements by pre-sum array, so `fill(flower, f, k)` is called in `O(log(n))`, which is the complexity of `cost(condition)` .\n\nFinally, we traverse the `flowers` linearly to consider `k` garden full and `n-k` gardens incomplete, the total score is `k*full + flower*partial`, in which `flower` is the max-min value of the `n-k` incomplete gardens, which is calculated by the binary search method above in `O(log(target)*log(n))`, along with a space complexity `O(n)`. (`n` = `len(flowers)`)\n\n\n```py\nimport bisect\nclass Solution:\n def maximumBeauty(self, flowers: List[int], newFlowers: int, target: int, full: int, partial: int) -> int:\n n = len(flowers)\n flowers.sort()\n pre,lack = [0],[0]\n \n # corner case in which no incomplete garden can be created. \n if flowers[0] >= target:\n return n*full\n \n # pre-sum in an ascending order\n for i in flowers:\n pre.append(pre[-1]+i)\n \n # pre-sum in a descending order, meanwhile, count how many gardens are already full\n cnt = 0\n for i in flowers[::-1]:\n if i >= target:\n cnt+=1\n lack.append(lack[-1]+max(target-i,0))\n \n # conditional checker: whether all first k elements can >= flower after adding f to them\n def fill(flower,f,k):\n i = bisect.bisect_left(flowers,flower,lo=0,hi=k)\n return pre[i] + f >= i*flower\n \n res = 0\n # start from the min number of full gardens\n for k in range(cnt,n):\n if lack[k] < newFlowers:\n left, right = flowers[0], target+1\n while left < right:\n mid = (left+right)//2\n if not fill(mid,newFlowers-lack[k],n-k):\n right = mid\n else:\n left = mid + 1\n left -= 1\n \n if left >= target:\n # the n-k gardens must be incomplete, which can have a max value as target-1\n \n res = max(res,(target-1)*partial+k*full)\n else:\n res = max(res,k*full+left*partial)\n \n # A corner case: All n gardens can be full, no incomplete gardens\n if lack[-1] <= newFlowers:\n res = max(res,n*full)\n return res\n \n \n```\nI know it looks ugly, but anyway, it is accepted.\n\n**Update**: credit to [@ithachien]() (see the comment below), I realize that in the last corner case (all gardens can be fulfilled) we don\'t have to do binary search to find out the max-min value of the first `n-k` gardens. It must be able to reach the largest min value as `target-1` because the remaining flowers are always sufficient, so I added the "short-circuitting" case before the loop as:\n\n```py\nres = 0\nif lack[-1] <= newFlowers:\n res = max(res,n*full)\n for k in range(cnt,n):\n res = max(res,(target-1)*partial+k*full)\n return res\n```\n\nBesides, the lower bound of the max-min value for the first `n-k` garden after planting the remaining flowers can be further increased to `(newFlowers-lack[k])//(n-k) + flowers[0]` as all flowers are evenly assigned to all `n-k` garden, which narrows down the search range.\n\nBased on the minor optimization above, my code turned out to be of a runtime in 2432 ms, and beats 100% Python3 submissions so far.
109,112
Minimum Number of Operations to Convert Time
minimum-number-of-operations-to-convert-time
You are given two strings current and correct representing two 24-hour times. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct.
String,Greedy
Easy
Convert the times to minutes. Use the operation with the biggest value possible at each step.
2,388
35
1. Convert times into minutes and then the problem becomes simpler. \n2. To minimize the number of total operations we try to use the largest possible change from `[60,15,5,1]` till possible.\n```\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n current_time = 60 * int(current[0:2]) + int(current[3:5]) # Current time in minutes\n target_time = 60 * int(correct[0:2]) + int(correct[3:5]) # Target time in minutes\n diff = target_time - current_time # Difference b/w current and target times in minutes\n count = 0 # Required number of operations\n\t\t# Use GREEDY APPROACH to calculate number of operations\n for i in [60, 15, 5, 1]:\n count += diff // i # add number of operations needed with i to count\n diff %= i # Diff becomes modulo of diff with i\n return count\n```\n
109,164
Minimum Number of Operations to Convert Time
minimum-number-of-operations-to-convert-time
You are given two strings current and correct representing two 24-hour times. 24-hour times are formatted as "HH:MM", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59. In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times. Return the minimum number of operations needed to convert current to correct.
String,Greedy
Easy
Convert the times to minutes. Use the operation with the biggest value possible at each step.
265
5
```\nclass Solution:\n def convertTime(self, current: str, correct: str) -> int:\n def toMinutes(s):\n h, m = s.split(\':\')\n return 60 * int(h) + int(m)\n \n minutes = toMinutes(correct) - toMinutes(current)\n hours, minutes = divmod(minutes, 60)\n quaters, minutes = divmod(minutes, 15)\n fives, minutes = divmod(minutes, 5)\n\n return hours + quaters + fives + minutes\n```
109,165
Add Two Integers
add-two-integers
null
Math
Easy
null
4,481
8
# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def sum(self, num1: int, num2: int) -> int:\n return num1 + num2\n```
109,236
Add Two Integers
add-two-integers
null
Math
Easy
null
4,508
12
**There\u2019s nothing to write on it write a recipe for pancakes**\n\n# Code\n```\nclass Solution:\n def sum(self, num1: int, num2: int) -> int:\n return num1 + num2\n \n```\n\n**Pancake Ingredients**\nYou likely already have everything you need to make this pancake recipe. If not, here\'s what to add to your grocery list:\n\n\xB7 Flour: This homemade pancake recipe starts with all-purpose flour.\n\xB7 Baking powder: Baking powder, a leavener, is the secret to fluffy pancakes.\n\xB7 Sugar: Just a tablespoon of white sugar is all you\'ll need for subtly sweet pancakes.\n\xB7 Salt: A pinch of salt will enhance the overall flavor without making your pancakes taste salty.\n\xB7 Milk and butter: Milk and butter add moisture and richness to the pancakes.\n\xB7 Egg: A whole egg lends even more moisture. Plus, it helps bind the pancake batter together.\n\n**How to Make Pancakes From Scratch**\nIt\'s not hard to make homemade pancakes \u2014 you just need a good recipe. That\'s where we come in! You\'ll find the step-by-step recipe below, but here\'s a brief overview of what you can expect:\n\n1. Sift the dry ingredients together.\n2. Make a well, then add the wet ingredients. Stir to combine.\n3. Scoop the batter onto a hot griddle or pan.\n4. Cook for two to three minutes, then flip.\n5. Continue cooking until brown on both sides.\n\n**When to Flip Pancakes**\nYour pancake will tell you when it\'s ready to flip. Wait until bubbles start to form on the top and the edges look dry and set. This will usually take about two to\nthree minutes on each side.\n\n# Code\n```\nclass Solution:\n def sum(self, num1: int, num2: int) -> int:\n return num1 + num2\n \n```
109,240
Add Two Integers
add-two-integers
null
Math
Easy
null
3,579
23
**1. C++**\n```\nclass Solution {\npublic:\n int sum(int num1, int num2) {\n return num1 + num2;\n }\n};\n```\n**2. Java**\n```\nclass Solution {\n public int sum(int num1, int num2) {\n return num1 + num2;\n }\n}\n```\n**3. Python3**\n```\nclass Solution:\n def sum(self, num1: int, num2: int) -> int:\n return num1 + num2\n```\n\u261D\uFE0F which is not actually necessary\n\nYou can do this instead:\n```\nclass Solution:\n sum = add\n```\n\n**4. C**\n```\nint sum(int num1, int num2){\n return num1 + num2;\n}\n```\n**5. C#**\n```\npublic class Solution {\n public int Sum(int num1, int num2) {\n return num1 + num2;\n }\n}\n```\n**6. JavaScript**\n```\nvar sum = function(num1, num2) {\n return num1 + num2;\n};\n```\n**7. Ruby**\n```\ndef sum(num1, num2)\n num1 + num2\nend\n```\n**8. Swift**\n```\nclass Solution {\n func sum(_ num1: Int, _ num2: Int) -> Int {\n return num1 + num2\n }\n}\n```\n**9. Go**\n```\nfunc sum(num1 int, num2 int) int {\n return num1 + num2\n}\n```\n**10. Scala**\n```\nobject Solution {\n def sum(num1: Int, num2: Int): Int = {\n return num1 + num2\n }\n}\n```\n**11. Kotlin**\n```\nclass Solution {\n fun sum(num1: Int, num2: Int): Int {\n return num1 + num2\n }\n}\n```\n**12. Rust**\n```\nimpl Solution {\n pub fn sum(num1: i32, num2: i32) -> i32 {\n return num1 + num2\n }\n}\n```\n**13. PHP**\n```\nclass Solution {\n function sum($num1, $num2) {\n return $num1 + $num2;\n }\n}\n```\n**14. Typescript**\n```\nfunction sum(num1: number, num2: number): number {\n return num1 + num2\n};\n```\n**15. Racket**\n```\n(define/contract (sum num1 num2)\n (-> exact-integer? exact-integer? exact-integer?)\n (+ num1 num2)\n )\n```\n**16. Erlang**\n```\n-spec sum(Num1 :: integer(), Num2 :: integer()) -> integer().\nsum(Num1, Num2) ->\n Num1 + Num2.\n```\n**17. Elixir**\n```\ndefmodule Solution do\n @spec sum(num1 :: integer, num2 :: integer) :: integer\n def sum(num1, num2) do\n num1 + num2\n end\nend\n```\n**18. Dart**\n```\nclass Solution {\n int sum(int num1, int num2) {\n return num1 + num2;\n }\n}\n```\nThat\'s it... Upvote if you liked this solution
109,242
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
1,979
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLOL U Still opened this ......\n# Code\n```\nNOTHING HERE BRO - SORRY !\n```
109,267
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
4,363
11
```\nclass Solution:\n def checkTree(self, root: Optional[TreeNode]) -> bool:\n return root.val==root.left.val+root.right.val\n```\n**An upvote will be encouraging**\n
109,272
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
7,051
15
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nDirect Tree approach ATTACKKKKKKKKK\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# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def checkTree(self, root: Optional[TreeNode]) -> bool:\n return root.val==root.left.val + root.right.val\n```
109,277
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
2,950
19
***Happy Coding..!* Feel free to ask Q\'s...**\n\n1. ***Golang Solution***\n```\n/**\n * Definition for a binary tree node.\n * type TreeNode struct {\n * Val int\n * Left *TreeNode\n * Right *TreeNode\n * }\n */\nfunc checkTree(root *TreeNode) bool {\n return root.Val == root.Left.Val + root.Right.Val\n}\n\n```\n\n2. ***Python Solution***\n```\nclass Solution(object):\n def checkTree(self, root):\n return root.val == root.left.val + root.right.val\n```\n3. ***Javascript Solution***\n```\n/**\n * @param {TreeNode} root\n * @return {boolean}\n */\n\nconst checkTree = root => root.val === (root.left.val + root.right.val);\n\n```\n\n// Tree Node\nfunction TreeNode(val, left, right) {\n this.val = (val === undefined ? 0 : val)\n this.left = (left === undefined ? null : left)\n this.right = (right === undefined ? null : right)\n}\n\n// Test Case 1\n// root = [10, 4, 6]\nlet tNode1 = new TreeNode(10);\nlet tNode2 = new TreeNode(4);\nlet tNode3 = new TreeNode(6);\n\ntNode1.left = tNode2;\ntNode1.right = tNode3;\n\nlet root = tNode1;\nconsole.log(checkTree(root)); // true\n\n\n***#happytohelpu***\n\n# ***Do upvote if you find this solution useful..***\n
109,279
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
3,618
17
```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def checkTree(self, root: Optional[TreeNode]) -> bool:\n # As per the def of binary tree node, we can compare the root value \\\n # with the TreeNode function, the root.left.val retrieves value of left node \\\n # the root.right.val retrieves value of right node. \'==\' compares two values\n if root.val == root.left.val + root.right.val: \n return True\n else:\n return False\n```
109,296
Root Equals Sum of Children
root-equals-sum-of-children
You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child. Return true if the value of the root is equal to the sum of the values of its two children, or false otherwise.
Tree,Binary Tree
Easy
null
5,828
19
```\nclass Solution:\n def checkTree(self, root: Optional[TreeNode]) -> bool:\n return root.val == (root.left.val + root.right.val)
109,298