title
stringlengths 1
100
| titleSlug
stringlengths 3
77
| Java
int64 0
1
| Python3
int64 1
1
| content
stringlengths 28
44.4k
| voteCount
int64 0
3.67k
| question_content
stringlengths 65
5k
| question_hints
stringclasses 970
values |
---|---|---|---|---|---|---|---|
Frequency Distribution - Clean code | maximum-equal-frequency | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe question states\n> every number that has appeared in it will have the same number of occurrences\n\nThis is a clear sign that at the core of the problem we need to keep track of the frequency of the frequencies of each number (call this `freq_dist`). To do this, we must keep track of the frequency of each number (call this num_freq`). \n\nA list will satisfy the constraints of the problem if it passes one of three cases:\n1. All the numbers have a frequency of 1\n2. A single number has a frequency of 1. The rest have a frequency of `max_num_freq`\n3. A single number has a frequency of `max_num_freq`. The rest have a frequency of `max_num_freq - 1`\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n* Enumerate the list. We are focused on the length so we will start with a count of 1.\n * We have seen a new number. Thus, we want to update our frequencies.\n * We have want to increment `num_freq`. This means that the `freq_dist` record associated with this number will be one too high. Thus, decrement it.\n * Now, we can increment the `num_freq` of this number.\n * Increment the `freq_dist` to reflect the change of `num_freq`\n * Finally, update `max_num_freq` to reflect the changes\n * Now that we have updated our `freq_dist` table, we can check if it satisfies our criteria. If the criteria is satisfied then we will save the new length to return at the end.\n * Case 1 can be evaluated by checking of the `max_num_freq` is 1.\n * Case 2 and 3 can be evaluated by using our `freq_dist` to translate our criteria into a arithmetic formula `freq_dist[single_appears] == 1 and (rest_appear * freq_dist[rest_appear] == total_size - single_appears) `\n\n# Complexity\n- Time complexity `O(n)`:\n - We are passing through the input list one time which is `O(n)`\n\n- Space complexity `O(n)`:\n - `num_freq` will store a frequency for each number in the input list. Thus, `O(n)`\n - `freq_dist` will store a frequency for every frequency in `num_freq`. This can certainly not exceed `O(n)` values. Thus, `O(n)`\n\n# Code\n```\n# On each iteration, check if the frequency distribution satisfies the constraints\n\nfrom collections import defaultdict\n\nclass Solution:\n def maxEqualFreq(self, nums: List[int]) -> int:\n num_freq = collections.defaultdict(int) # frequency of numbers\n freq_dist = collections.defaultdict(int) # distribution of frequencies\n max_num_freq = 0 # max count of numbers\n res = 0 \n\n def equation(single_appears, rest_appear, total_size):\n return freq_dist[single_appears] == 1 and (rest_appear * freq_dist[rest_appear] == total_size - single_appears) \n\n def isSatisfied(total_size):\n case_1 = (max_num_freq == 1) # All appear once.\n case_2 = equation(1, max_num_freq, total_size) # single appears once. Rest appear max_num_freq. \n case_3 = equation(max_num_freq, max_num_freq - 1, total_size) # single appears max_num_freq. Rest appear max_num_freq-1\n \n return case_1 or case_2 or case_3\n\n for length, num in enumerate(nums, 1):\n # We have a new number\n # First, decrement the freq_dist since this is now out of date\n freq_dist[num_freq[num]] -= 1\n\n # Now, increment the num_freq of this number. Remember to update the new freq_dist\n num_freq[num] += 1 \n freq_dist[num_freq[num]] += 1\n\n # Update the new max_num_freq\n max_num_freq = max(max_num_freq, num_freq[num])\n \n if isSatisfied(length):\n res = length\n return res\n\n``` | 0 | Given two numbers, `hour` and `minutes`, return _the smaller angle (in degrees) formed between the_ `hour` _and the_ `minute` _hand_.
Answers within `10-5` of the actual value will be accepted as correct.
**Example 1:**
**Input:** hour = 12, minutes = 30
**Output:** 165
**Example 2:**
**Input:** hour = 3, minutes = 30
**Output:** 75
**Example 3:**
**Input:** hour = 3, minutes = 15
**Output:** 7.5
**Constraints:**
* `1 <= hour <= 12`
* `0 <= minutes <= 59` | Keep track of the min and max frequencies. The number to be eliminated must have a frequency of 1, same as the others or the same +1. |
Python (Simple Hashmap) | maximum-equal-frequency | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxEqualFreq(self, nums):\n dict1, dict2, max_len = collections.defaultdict(int), collections.defaultdict(int), 0\n\n for i,j in enumerate(nums):\n dict1[j] += 1\n dict2[dict1[j]] += 1\n\n val = dict2[dict1[j]]*dict1[j]\n\n if val == i+1 and i != len(nums)-1:\n max_len = max(max_len,i+2)\n elif val == i:\n max_len = max(max_len,i+1)\n\n return max_len\n\n\n\n\n \n``` | 0 | Given an array `nums` of positive integers, return the longest possible length of an array prefix of `nums`, such that it is possible to remove **exactly one** element from this prefix so that every number that has appeared in it will have the same number of occurrences.
If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).
**Example 1:**
**Input:** nums = \[2,2,1,1,5,3,3,5\]
**Output:** 7
**Explanation:** For the subarray \[2,2,1,1,5,3,3\] of length 7, if we remove nums\[4\] = 5, we will get \[2,2,1,1,3,3\], so that each number will appear exactly twice.
**Example 2:**
**Input:** nums = \[1,1,1,2,2,2,3,3,3,4,4,4,5\]
**Output:** 13
**Constraints:**
* `2 <= nums.length <= 105`
* `1 <= nums[i] <= 105` | Use dynamic programming. Let dp[i][j] be the answer for the first i rows such that column j is chosen from row i. Use the concept of cumulative array to optimize the complexity of the solution. |
Python (Simple Hashmap) | maximum-equal-frequency | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxEqualFreq(self, nums):\n dict1, dict2, max_len = collections.defaultdict(int), collections.defaultdict(int), 0\n\n for i,j in enumerate(nums):\n dict1[j] += 1\n dict2[dict1[j]] += 1\n\n val = dict2[dict1[j]]*dict1[j]\n\n if val == i+1 and i != len(nums)-1:\n max_len = max(max_len,i+2)\n elif val == i:\n max_len = max(max_len,i+1)\n\n return max_len\n\n\n\n\n \n``` | 0 | Given two numbers, `hour` and `minutes`, return _the smaller angle (in degrees) formed between the_ `hour` _and the_ `minute` _hand_.
Answers within `10-5` of the actual value will be accepted as correct.
**Example 1:**
**Input:** hour = 12, minutes = 30
**Output:** 165
**Example 2:**
**Input:** hour = 3, minutes = 30
**Output:** 75
**Example 3:**
**Input:** hour = 3, minutes = 15
**Output:** 7.5
**Constraints:**
* `1 <= hour <= 12`
* `0 <= minutes <= 59` | Keep track of the min and max frequencies. The number to be eliminated must have a frequency of 1, same as the others or the same +1. |
Python3: Count collections | maximum-equal-frequency | 0 | 1 | The basic idea is to first count the occurence of each number in `nums`.\nThen, count the counts--i.e. count the occurrence groups. \nThe solution must be 1 of a few scenarios (there were more trivial scenarios then I thought - leading to bad submissions).\nIf the count of counts is not one such scenario: `nums.pop()` and re-evaluate.\n\nHere are the possible, valid scenarios:\n`length of count of counts == 1`\n1.There is only one number in `nums` (count of counts looks like this: `{n:1}` )\n2. There is only one count of each distinct number (count of counts looks like this: `{1:m}` )\n\n`len(count of counts) == 2`\n3. All numbers occur the same number of times, except a SINGLE occurence of some other number ( `{n:m,1:1}` )\n4. All numbers occur the same number of times, except one number occurs one additional time: ( `{n:m, n+1:1}` ) \n\n```\nfrom collections import Counter\n\nclass Solution:\n def maxEqualFreq(self, nums: List[int]) -> int:\n dic = Counter(nums)\n dicdic = Counter(list(dic.values()))\n if len(nums) == 2:\n return 2\n \n while True:\n if len(dicdic) == 1 and (min(dicdic) == 1 or min(dicdic.values()) == 1):\n return len(nums) \n if len(dicdic) == 2:\n max_dicdic_keys = max(dicdic)\n min_dicdic_keys = min(dicdic)\n if max_dicdic_keys - min_dicdic_keys == 1 and dicdic[max_dicdic_keys] == 1:\n return len(nums)\n if min_dicdic_keys == 1 and dicdic[min_dicdic_keys] == 1:\n return len(nums)\n cleanup = nums.pop()\n if dic[cleanup] - 1 == 0:\n del dic[cleanup]\n else:\n dic[cleanup] = dic[cleanup] -1\n dicdic = Counter(list(dic.values()))\n \n return\n``` | 3 | Given an array `nums` of positive integers, return the longest possible length of an array prefix of `nums`, such that it is possible to remove **exactly one** element from this prefix so that every number that has appeared in it will have the same number of occurrences.
If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).
**Example 1:**
**Input:** nums = \[2,2,1,1,5,3,3,5\]
**Output:** 7
**Explanation:** For the subarray \[2,2,1,1,5,3,3\] of length 7, if we remove nums\[4\] = 5, we will get \[2,2,1,1,3,3\], so that each number will appear exactly twice.
**Example 2:**
**Input:** nums = \[1,1,1,2,2,2,3,3,3,4,4,4,5\]
**Output:** 13
**Constraints:**
* `2 <= nums.length <= 105`
* `1 <= nums[i] <= 105` | Use dynamic programming. Let dp[i][j] be the answer for the first i rows such that column j is chosen from row i. Use the concept of cumulative array to optimize the complexity of the solution. |
Python3: Count collections | maximum-equal-frequency | 0 | 1 | The basic idea is to first count the occurence of each number in `nums`.\nThen, count the counts--i.e. count the occurrence groups. \nThe solution must be 1 of a few scenarios (there were more trivial scenarios then I thought - leading to bad submissions).\nIf the count of counts is not one such scenario: `nums.pop()` and re-evaluate.\n\nHere are the possible, valid scenarios:\n`length of count of counts == 1`\n1.There is only one number in `nums` (count of counts looks like this: `{n:1}` )\n2. There is only one count of each distinct number (count of counts looks like this: `{1:m}` )\n\n`len(count of counts) == 2`\n3. All numbers occur the same number of times, except a SINGLE occurence of some other number ( `{n:m,1:1}` )\n4. All numbers occur the same number of times, except one number occurs one additional time: ( `{n:m, n+1:1}` ) \n\n```\nfrom collections import Counter\n\nclass Solution:\n def maxEqualFreq(self, nums: List[int]) -> int:\n dic = Counter(nums)\n dicdic = Counter(list(dic.values()))\n if len(nums) == 2:\n return 2\n \n while True:\n if len(dicdic) == 1 and (min(dicdic) == 1 or min(dicdic.values()) == 1):\n return len(nums) \n if len(dicdic) == 2:\n max_dicdic_keys = max(dicdic)\n min_dicdic_keys = min(dicdic)\n if max_dicdic_keys - min_dicdic_keys == 1 and dicdic[max_dicdic_keys] == 1:\n return len(nums)\n if min_dicdic_keys == 1 and dicdic[min_dicdic_keys] == 1:\n return len(nums)\n cleanup = nums.pop()\n if dic[cleanup] - 1 == 0:\n del dic[cleanup]\n else:\n dic[cleanup] = dic[cleanup] -1\n dicdic = Counter(list(dic.values()))\n \n return\n``` | 3 | Given two numbers, `hour` and `minutes`, return _the smaller angle (in degrees) formed between the_ `hour` _and the_ `minute` _hand_.
Answers within `10-5` of the actual value will be accepted as correct.
**Example 1:**
**Input:** hour = 12, minutes = 30
**Output:** 165
**Example 2:**
**Input:** hour = 3, minutes = 30
**Output:** 75
**Example 3:**
**Input:** hour = 3, minutes = 15
**Output:** 7.5
**Constraints:**
* `1 <= hour <= 12`
* `0 <= minutes <= 59` | Keep track of the min and max frequencies. The number to be eliminated must have a frequency of 1, same as the others or the same +1. |
[Python] | Left-right for even; right-left for odd philosophers | the-dining-philosophers | 0 | 1 | # Intuition\nCreate a Lock for each fork. Each philosopher tries to acquire 2 forks adjacent to him, before eating\n\nIf all philosophers take the fork to the left first, there can be a deadlock, when all of them got only 1 fork.\n\n# Approach\nTo resolve the deadlock, make even philosopers take left first, then right. And for odd ones - vice versa.\n\n# Code\n```\nfrom threading import Lock\n\nclass DiningPhilosophers:\n def __init__(self):\n self.forks = [Lock() for _ in range(5)]\n\n # call the functions directly to execute, for example, eat()\n def wantsToEat(self,\n philosopher: int,\n pickLeftFork: \'Callable[[], None]\',\n pickRightFork: \'Callable[[], None]\',\n eat: \'Callable[[], None]\',\n putLeftFork: \'Callable[[], None]\',\n putRightFork: \'Callable[[], None]\') -> None:\n \n left_fork, right_fork = self.forks[philosopher], self.forks[philosopher - 1]\n \n #for even philosopers pick first left then right, for odd - first right then left\n if philosopher%2: \n first_fork, second_fork = right_fork, left_fork\n else:\n first_fork, second_fork = left_fork, right_fork\n\n with first_fork, second_fork:\n pickLeftFork()\n pickRightFork()\n eat()\n putRightFork()\n putLeftFork()\n``` | 3 | Given an array of integers `arr` and an integer `d`. In one step you can jump from index `i` to index:
* `i + x` where: `i + x < arr.length` and `0 < x <= d`.
* `i - x` where: `i - x >= 0` and `0 < x <= d`.
In addition, you can only jump from index `i` to index `j` if `arr[i] > arr[j]` and `arr[i] > arr[k]` for all indices `k` between `i` and `j` (More formally `min(i, j) < k < max(i, j)`).
You can choose any index of the array and start jumping. Return _the maximum number of indices_ you can visit.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Input:** arr = \[6,4,14,6,8,13,9,7,10,6,12\], d = 2
**Output:** 4
**Explanation:** You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.
Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.
Similarly You cannot jump from index 3 to index 2 or index 1.
**Example 2:**
**Input:** arr = \[3,3,3,3,3\], d = 3
**Output:** 1
**Explanation:** You can start at any index. You always cannot jump to any index.
**Example 3:**
**Input:** arr = \[7,6,5,4,3,2,1\], d = 1
**Output:** 7
**Explanation:** Start at index 0. You can visit all the indicies.
**Constraints:**
* `1 <= arr.length <= 1000`
* `1 <= arr[i] <= 105`
* `1 <= d <= arr.length` | null |
Simple python solution using lock ordering | the-dining-philosophers | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTake locks in sorted order. Philosopher 0 must take fork 0 before he takes fork 1, this means philosopher 4 takes fork 0 before he takes fork 4.\n\nSo only one of them will take the fork 0 and the other will wait. Since we have to have one who doesn\'t take anything that means that the the one next to him will be able to get two.\n\n\n# Code\n```\nfrom threading import Lock, Semaphore\n\nclass DiningPhilosophers:\n\n def __init__(self):\n self.forks = [Lock() for _ in range(5)]\n\n # call the functions directly to execute, for example, eat()\n def wantsToEat(self,\n philosopher: int,\n pickLeftFork: \'Callable[[], None]\',\n pickRightFork: \'Callable[[], None]\',\n eat: \'Callable[[], None]\',\n putLeftFork: \'Callable[[], None]\',\n putRightFork: \'Callable[[], None]\') -> None:\n\n left, right = self.left_fork(philosopher), self.right_fork(philosopher)\n\n if left > right:\n left, right = right, left\n pickLeftFork, pickRightFork = pickRightFork, pickLeftFork\n putLeftFork, putRightFork = putRightFork, putLeftFork\n \n with self.forks[left]:\n pickLeftFork()\n with self.forks[right]:\n pickRightFork()\n eat()\n \n putLeftFork()\n putRightFork()\n\n def left_fork(self, i):\n return (i + 1) % 5\n \n def right_fork(self, i):\n return i\n``` | 0 | Given an array of integers `arr` and an integer `d`. In one step you can jump from index `i` to index:
* `i + x` where: `i + x < arr.length` and `0 < x <= d`.
* `i - x` where: `i - x >= 0` and `0 < x <= d`.
In addition, you can only jump from index `i` to index `j` if `arr[i] > arr[j]` and `arr[i] > arr[k]` for all indices `k` between `i` and `j` (More formally `min(i, j) < k < max(i, j)`).
You can choose any index of the array and start jumping. Return _the maximum number of indices_ you can visit.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Input:** arr = \[6,4,14,6,8,13,9,7,10,6,12\], d = 2
**Output:** 4
**Explanation:** You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.
Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.
Similarly You cannot jump from index 3 to index 2 or index 1.
**Example 2:**
**Input:** arr = \[3,3,3,3,3\], d = 3
**Output:** 1
**Explanation:** You can start at any index. You always cannot jump to any index.
**Example 3:**
**Input:** arr = \[7,6,5,4,3,2,1\], d = 1
**Output:** 7
**Explanation:** Start at index 0. You can visit all the indicies.
**Constraints:**
* `1 <= arr.length <= 1000`
* `1 <= arr[i] <= 105`
* `1 <= d <= arr.length` | null |
Python 4 locks() with some explanation | the-dining-philosophers | 0 | 1 | Beats 100.00%\n\n# Code\n```\nfrom threading import Lock\n\nclass DiningPhilosophers:\n\n # class variables single copy exists\n even=Lock()\n seam=[Lock() for _ in range(5)]\n\n # call the functions directly to execute, for example, eat()\n def wantsToEat(self,\n i: int,\n pickLeftFork: \'Callable[[], None]\',\n pickRightFork: \'Callable[[], None]\',\n eat: \'Callable[[], None]\',\n putLeftFork: \'Callable[[], None]\',\n putRightFork: \'Callable[[], None]\') -> None:\n if i%2==0:\n self.even.acquire()\n left=i\n right=(i+1)%5\n\n\n # if anyfork below not available program waits. deadlock ia only cyclic here.\n # so if i break cycle by preventing more than 2 philo to reach till this comment\n # because even doesnt allow them to come till here, deadlock is prevented\n self.seam[left].acquire()\n self.seam[right].acquire()\n pickRightFork()\n pickLeftFork()\n eat()\n putLeftFork()\n putRightFork()\n self.seam[left].release()\n self.seam[right].release()\n if i%2==0:\n self.even.release()\n\n \n\n``` | 0 | Given an array of integers `arr` and an integer `d`. In one step you can jump from index `i` to index:
* `i + x` where: `i + x < arr.length` and `0 < x <= d`.
* `i - x` where: `i - x >= 0` and `0 < x <= d`.
In addition, you can only jump from index `i` to index `j` if `arr[i] > arr[j]` and `arr[i] > arr[k]` for all indices `k` between `i` and `j` (More formally `min(i, j) < k < max(i, j)`).
You can choose any index of the array and start jumping. Return _the maximum number of indices_ you can visit.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Input:** arr = \[6,4,14,6,8,13,9,7,10,6,12\], d = 2
**Output:** 4
**Explanation:** You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.
Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.
Similarly You cannot jump from index 3 to index 2 or index 1.
**Example 2:**
**Input:** arr = \[3,3,3,3,3\], d = 3
**Output:** 1
**Explanation:** You can start at any index. You always cannot jump to any index.
**Example 3:**
**Input:** arr = \[7,6,5,4,3,2,1\], d = 1
**Output:** 7
**Explanation:** Start at index 0. You can visit all the indicies.
**Constraints:**
* `1 <= arr.length <= 1000`
* `1 <= arr[i] <= 105`
* `1 <= d <= arr.length` | null |
Basic solution | airplane-seat-assignment-probability | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nHe will get his seat or he will lose his seat.\n\n# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n return 1/2 if n>1 else 1\n``` | 0 | `n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
* Take their own seat if it is still available, and
* Pick other seats randomly when they find their seat occupied
Return _the probability that the_ `nth` _person gets his own seat_.
**Example 1:**
**Input:** n = 1
**Output:** 1.00000
**Explanation:** The first person can only get the first seat.
**Example 2:**
**Input:** n = 2
**Output:** 0.50000
**Explanation:** The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).
**Constraints:**
* `1 <= n <= 105` | For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap. |
Basic solution | airplane-seat-assignment-probability | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nHe will get his seat or he will lose his seat.\n\n# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n return 1/2 if n>1 else 1\n``` | 0 | Given an integer `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`.
Return the two integers in any order.
**Example 1:**
**Input:** num = 8
**Output:** \[3,3\]
**Explanation:** For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.
**Example 2:**
**Input:** num = 123
**Output:** \[5,25\]
**Example 3:**
**Input:** num = 999
**Output:** \[40,25\]
**Constraints:**
* `1 <= num <= 10^9` | Let f(n) denote the probability of the n-th person getting correct seat in n-person case, then:
f(1) = 1 (base case, trivial)
f(2) = 1/2 (also trivial) Try to calculate f(3), f(4), and f(5) using the base cases. What if the value of them?
f(i) for i >= 2 will also be 1/2. Try to proof why f(i) = 1/2 for i >= 2. |
Airplane seat assignment probability | airplane-seat-assignment-probability | 0 | 1 | # Intuition\n\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 nthPersonGetsNthSeat(self, n: int) -> float:\n if n==1:\n return 1/n\n else:\n return 1/2\n``` | 1 | `n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
* Take their own seat if it is still available, and
* Pick other seats randomly when they find their seat occupied
Return _the probability that the_ `nth` _person gets his own seat_.
**Example 1:**
**Input:** n = 1
**Output:** 1.00000
**Explanation:** The first person can only get the first seat.
**Example 2:**
**Input:** n = 2
**Output:** 0.50000
**Explanation:** The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).
**Constraints:**
* `1 <= n <= 105` | For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap. |
Airplane seat assignment probability | airplane-seat-assignment-probability | 0 | 1 | # Intuition\n\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 nthPersonGetsNthSeat(self, n: int) -> float:\n if n==1:\n return 1/n\n else:\n return 1/2\n``` | 1 | Given an integer `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`.
Return the two integers in any order.
**Example 1:**
**Input:** num = 8
**Output:** \[3,3\]
**Explanation:** For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.
**Example 2:**
**Input:** num = 123
**Output:** \[5,25\]
**Example 3:**
**Input:** num = 999
**Output:** \[40,25\]
**Constraints:**
* `1 <= num <= 10^9` | Let f(n) denote the probability of the n-th person getting correct seat in n-person case, then:
f(1) = 1 (base case, trivial)
f(2) = 1/2 (also trivial) Try to calculate f(3), f(4), and f(5) using the base cases. What if the value of them?
f(i) for i >= 2 will also be 1/2. Try to proof why f(i) = 1/2 for i >= 2. |
Middle school solution, Just counting cases. | airplane-seat-assignment-probability | 0 | 1 | Let n = 10\n\nTake one case for example: \n\nFirst person took **seat 3**, third person then sit on **seat 7**, and the seventh person sit on **seat 1**. \n\nThen we write down the sequence **[3, 7, 1]** to represent what just happened.\n\nNow every case corresponds to a sequence and vice versa. These sequence must be:\n\n-Ended with 1.\n-Increasing excludes the last 1 (because person 1 to 10 aboard orderly).\n\nBy writing down the sequences, it is easily to find that there are equal number of sequence with or without 10 in it. \n(Just add a 10 to whatever doesn\'t have a 10 gives an unique sequence)\n\nSo it\'s 1/2\n\n\n \n | 1 | `n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
* Take their own seat if it is still available, and
* Pick other seats randomly when they find their seat occupied
Return _the probability that the_ `nth` _person gets his own seat_.
**Example 1:**
**Input:** n = 1
**Output:** 1.00000
**Explanation:** The first person can only get the first seat.
**Example 2:**
**Input:** n = 2
**Output:** 0.50000
**Explanation:** The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).
**Constraints:**
* `1 <= n <= 105` | For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap. |
Middle school solution, Just counting cases. | airplane-seat-assignment-probability | 0 | 1 | Let n = 10\n\nTake one case for example: \n\nFirst person took **seat 3**, third person then sit on **seat 7**, and the seventh person sit on **seat 1**. \n\nThen we write down the sequence **[3, 7, 1]** to represent what just happened.\n\nNow every case corresponds to a sequence and vice versa. These sequence must be:\n\n-Ended with 1.\n-Increasing excludes the last 1 (because person 1 to 10 aboard orderly).\n\nBy writing down the sequences, it is easily to find that there are equal number of sequence with or without 10 in it. \n(Just add a 10 to whatever doesn\'t have a 10 gives an unique sequence)\n\nSo it\'s 1/2\n\n\n \n | 1 | Given an integer `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`.
Return the two integers in any order.
**Example 1:**
**Input:** num = 8
**Output:** \[3,3\]
**Explanation:** For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.
**Example 2:**
**Input:** num = 123
**Output:** \[5,25\]
**Example 3:**
**Input:** num = 999
**Output:** \[40,25\]
**Constraints:**
* `1 <= num <= 10^9` | Let f(n) denote the probability of the n-th person getting correct seat in n-person case, then:
f(1) = 1 (base case, trivial)
f(2) = 1/2 (also trivial) Try to calculate f(3), f(4), and f(5) using the base cases. What if the value of them?
f(i) for i >= 2 will also be 1/2. Try to proof why f(i) = 1/2 for i >= 2. |
0.5 if n > 1 else 1 Math Proof | airplane-seat-assignment-probability | 0 | 1 | # Math Solution\nLet $S = \\{p_1, p_2, p_3, p_4, \\cdots , p_n\\}$ be a set of $n$ person where $p_1$ picks a random seat.\nLet $p(n)$ = probability of $p_n$ getting their seat.\n\n## Base Cases\n$S = \\{p_1\\}$, $p(1) = 1$\n$S = \\{p_1, p_2\\}$, $p(2) = 0.5$\n\n## For $n > 2$\nIf $p_1$ takes their correct seat then all others sit in their own seat and $p_n$ always gets the correct seat. So in this case the probability is $1.0$ and this happens with a probability of $\\frac{1}{n}$.\n\nIf $p_1$ takes $p_n$\'s seat everyone takes their own seat but $p_n$ never get their seat. So in this case the probability is $0$. \n\nIf $p_1$ takes $p_k$\'s seat ($k \\ne n)$ everyone from $p_2, p_3,..., p_{k-1}$ sees their seat not occupied and sits on that. Then $p_k$ sees their seat occupied and picks a random seat. Consider $S\' = \\{p_k, p_{k+1}, p_{k+2}, ..., p_n\\}$ is the same sub problem where $p_k$ takes a random seat with size = $n - k + 1$. So in this case the probability of $p_n$ getting their own seat is $p(n-k+1)$ and this case occurs with a probability of $\\frac{1}{n}$.\n\n$\n\\therefore \\displaystyle{\n p(n) = \\frac{1}{n} \\cdot 1 + \\sum_{k = 2}^{n-1} \\frac{1}{n} \\cdot p(n-k+1)\n}\n$ for $n > 2$\n\n$\n\\implies \\displaystyle{\n n \\cdot p(n) = 1 + \\sum_{k = 2}^{n-1} p(n-k+1)\n}\n$\n$= 1 + p(n-1) + p(n-2) + \\cdots + p(2)$\n$= p(n-1) + (1 + p(n-2) + \\cdots + p(2))$\n$= p(n-1) + (n-1) \\cdot p(n-1)$\n$= n \\cdot p(n-1)$\n$\\therefore p(n) = p(n-1)$ for $n > 2$\n\nFinally, $p(n) = p(n-1) = p(n-2) = \\cdots = p(3) = p(2) = 0.5$ for $n > 2$\n\nThis gives the solution,\n$p(n) = 1$ if $n = 1$ else $0.5$\n\n# Complexity\n- Time complexity: $O(1)$\n- Space complexity: $O(1)$\n\n# Code\n```py\nclass Solution:\n def nthPersonGetsNthSeat(self, n):\n return 0.5 if n > 1 else 1\n``` | 4 | `n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
* Take their own seat if it is still available, and
* Pick other seats randomly when they find their seat occupied
Return _the probability that the_ `nth` _person gets his own seat_.
**Example 1:**
**Input:** n = 1
**Output:** 1.00000
**Explanation:** The first person can only get the first seat.
**Example 2:**
**Input:** n = 2
**Output:** 0.50000
**Explanation:** The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).
**Constraints:**
* `1 <= n <= 105` | For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap. |
0.5 if n > 1 else 1 Math Proof | airplane-seat-assignment-probability | 0 | 1 | # Math Solution\nLet $S = \\{p_1, p_2, p_3, p_4, \\cdots , p_n\\}$ be a set of $n$ person where $p_1$ picks a random seat.\nLet $p(n)$ = probability of $p_n$ getting their seat.\n\n## Base Cases\n$S = \\{p_1\\}$, $p(1) = 1$\n$S = \\{p_1, p_2\\}$, $p(2) = 0.5$\n\n## For $n > 2$\nIf $p_1$ takes their correct seat then all others sit in their own seat and $p_n$ always gets the correct seat. So in this case the probability is $1.0$ and this happens with a probability of $\\frac{1}{n}$.\n\nIf $p_1$ takes $p_n$\'s seat everyone takes their own seat but $p_n$ never get their seat. So in this case the probability is $0$. \n\nIf $p_1$ takes $p_k$\'s seat ($k \\ne n)$ everyone from $p_2, p_3,..., p_{k-1}$ sees their seat not occupied and sits on that. Then $p_k$ sees their seat occupied and picks a random seat. Consider $S\' = \\{p_k, p_{k+1}, p_{k+2}, ..., p_n\\}$ is the same sub problem where $p_k$ takes a random seat with size = $n - k + 1$. So in this case the probability of $p_n$ getting their own seat is $p(n-k+1)$ and this case occurs with a probability of $\\frac{1}{n}$.\n\n$\n\\therefore \\displaystyle{\n p(n) = \\frac{1}{n} \\cdot 1 + \\sum_{k = 2}^{n-1} \\frac{1}{n} \\cdot p(n-k+1)\n}\n$ for $n > 2$\n\n$\n\\implies \\displaystyle{\n n \\cdot p(n) = 1 + \\sum_{k = 2}^{n-1} p(n-k+1)\n}\n$\n$= 1 + p(n-1) + p(n-2) + \\cdots + p(2)$\n$= p(n-1) + (1 + p(n-2) + \\cdots + p(2))$\n$= p(n-1) + (n-1) \\cdot p(n-1)$\n$= n \\cdot p(n-1)$\n$\\therefore p(n) = p(n-1)$ for $n > 2$\n\nFinally, $p(n) = p(n-1) = p(n-2) = \\cdots = p(3) = p(2) = 0.5$ for $n > 2$\n\nThis gives the solution,\n$p(n) = 1$ if $n = 1$ else $0.5$\n\n# Complexity\n- Time complexity: $O(1)$\n- Space complexity: $O(1)$\n\n# Code\n```py\nclass Solution:\n def nthPersonGetsNthSeat(self, n):\n return 0.5 if n > 1 else 1\n``` | 4 | Given an integer `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`.
Return the two integers in any order.
**Example 1:**
**Input:** num = 8
**Output:** \[3,3\]
**Explanation:** For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.
**Example 2:**
**Input:** num = 123
**Output:** \[5,25\]
**Example 3:**
**Input:** num = 999
**Output:** \[40,25\]
**Constraints:**
* `1 <= num <= 10^9` | Let f(n) denote the probability of the n-th person getting correct seat in n-person case, then:
f(1) = 1 (base case, trivial)
f(2) = 1/2 (also trivial) Try to calculate f(3), f(4), and f(5) using the base cases. What if the value of them?
f(i) for i >= 2 will also be 1/2. Try to proof why f(i) = 1/2 for i >= 2. |
Python3 DP with explanation | airplane-seat-assignment-probability | 0 | 1 | Basically, we model dp[n] = P(n). We start with base cases dp[1] = 1.0, and dp[2] = 0.5.\nWhat is dp[3]? If n = 3, and first person picks his own seat (1/n chance), then we get 1/n * P(1). if the first person picks the 2nd seat (1/n chance), then the second person has to pick between two seats, so we get 1/n * P(2). Therefore, P(3) = 1/n * P(1) + 1/n * P(2). In general, we can write:\n```\nP(n) = (1/n) * (P(n - 1) + P(n - 2) + P(n - 3) ... + P(1))\n```\nSo I keep track of the accumulated sum using a variable called \'acc\'.\n```\nclass Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n if n == 1:\n return 1\n if n == 2:\n return 0.5\n dp = [0] * (n + 1)\n dp[1] = 1\n dp[2] = 0.5\n acc = 1.5\n for i in range(3, n + 1):\n dp[i] = (1.0 / i) * acc\n acc += dp[i]\n return dp[-1]\n``` | 12 | `n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
* Take their own seat if it is still available, and
* Pick other seats randomly when they find their seat occupied
Return _the probability that the_ `nth` _person gets his own seat_.
**Example 1:**
**Input:** n = 1
**Output:** 1.00000
**Explanation:** The first person can only get the first seat.
**Example 2:**
**Input:** n = 2
**Output:** 0.50000
**Explanation:** The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).
**Constraints:**
* `1 <= n <= 105` | For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap. |
Python3 DP with explanation | airplane-seat-assignment-probability | 0 | 1 | Basically, we model dp[n] = P(n). We start with base cases dp[1] = 1.0, and dp[2] = 0.5.\nWhat is dp[3]? If n = 3, and first person picks his own seat (1/n chance), then we get 1/n * P(1). if the first person picks the 2nd seat (1/n chance), then the second person has to pick between two seats, so we get 1/n * P(2). Therefore, P(3) = 1/n * P(1) + 1/n * P(2). In general, we can write:\n```\nP(n) = (1/n) * (P(n - 1) + P(n - 2) + P(n - 3) ... + P(1))\n```\nSo I keep track of the accumulated sum using a variable called \'acc\'.\n```\nclass Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n if n == 1:\n return 1\n if n == 2:\n return 0.5\n dp = [0] * (n + 1)\n dp[1] = 1\n dp[2] = 0.5\n acc = 1.5\n for i in range(3, n + 1):\n dp[i] = (1.0 / i) * acc\n acc += dp[i]\n return dp[-1]\n``` | 12 | Given an integer `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`.
Return the two integers in any order.
**Example 1:**
**Input:** num = 8
**Output:** \[3,3\]
**Explanation:** For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.
**Example 2:**
**Input:** num = 123
**Output:** \[5,25\]
**Example 3:**
**Input:** num = 999
**Output:** \[40,25\]
**Constraints:**
* `1 <= num <= 10^9` | Let f(n) denote the probability of the n-th person getting correct seat in n-person case, then:
f(1) = 1 (base case, trivial)
f(2) = 1/2 (also trivial) Try to calculate f(3), f(4), and f(5) using the base cases. What if the value of them?
f(i) for i >= 2 will also be 1/2. Try to proof why f(i) = 1/2 for i >= 2. |
1 line | airplane-seat-assignment-probability | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n return 0.5 if n>1 else n\n``` | 0 | `n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
* Take their own seat if it is still available, and
* Pick other seats randomly when they find their seat occupied
Return _the probability that the_ `nth` _person gets his own seat_.
**Example 1:**
**Input:** n = 1
**Output:** 1.00000
**Explanation:** The first person can only get the first seat.
**Example 2:**
**Input:** n = 2
**Output:** 0.50000
**Explanation:** The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).
**Constraints:**
* `1 <= n <= 105` | For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap. |
1 line | airplane-seat-assignment-probability | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n return 0.5 if n>1 else n\n``` | 0 | Given an integer `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`.
Return the two integers in any order.
**Example 1:**
**Input:** num = 8
**Output:** \[3,3\]
**Explanation:** For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.
**Example 2:**
**Input:** num = 123
**Output:** \[5,25\]
**Example 3:**
**Input:** num = 999
**Output:** \[40,25\]
**Constraints:**
* `1 <= num <= 10^9` | Let f(n) denote the probability of the n-th person getting correct seat in n-person case, then:
f(1) = 1 (base case, trivial)
f(2) = 1/2 (also trivial) Try to calculate f(3), f(4), and f(5) using the base cases. What if the value of them?
f(i) for i >= 2 will also be 1/2. Try to proof why f(i) = 1/2 for i >= 2. |
1232. Check If It Is a Straight Line Solution in Python | check-if-it-is-a-straight-line | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nHere\'s a breakdown of how the code works:\n\n1. It starts by getting the number of coordinates in the input list, denoted as n.\n\n2. It then extracts the x and y coordinates of the first two points (the 0th and 1st elements) from the input list.\n\n3. The code enters a loop that iterates through the remaining coordinates (from index 2 to n-1).\n\n4. For each coordinate (x, y) in the loop, it checks whether the condition (y - y1) * (x - x2) != (y - y2) * (x - x1) is satisfied. This condition is checking if the slopes between the current point and the first two points are equal. If this condition is not met for any point, the method returns False, indicating that the points do not lie on a straight line.\n\n5. If the loop completes without finding any point that breaks the condition, the method returns True, indicating that all the points form a straight line.\n\nThis code is implementing a mathematical concept to check if a set of points is collinear (lies on a straight line) by comparing the slopes between the first two points and all other points. If all slopes are equal, the points are collinear; otherwise, they are not.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def checkStraightLine(self, coordinates: List[List[int]]) -> bool:\n n = len(coordinates)\n\n x1, y1 = coordinates[0]\n x2, y2 = coordinates[1]\n\n for i in range(2, n):\n x, y = coordinates[i]\n\n if (y - y1) * (x - x2) != (y - y2) * (x - x1):\n return False\n\n return True\n``` | 1 | You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane.
**Example 1:**
**Input:** coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\]
**Output:** true
**Example 2:**
**Input:** coordinates = \[\[1,1\],\[2,2\],\[3,4\],\[4,5\],\[5,6\],\[7,7\]\]
**Output:** false
**Constraints:**
* `2 <= coordinates.length <= 1000`
* `coordinates[i].length == 2`
* `-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4`
* `coordinates` contains no duplicate point. | If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value. |
1232. Check If It Is a Straight Line Solution in Python | check-if-it-is-a-straight-line | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nHere\'s a breakdown of how the code works:\n\n1. It starts by getting the number of coordinates in the input list, denoted as n.\n\n2. It then extracts the x and y coordinates of the first two points (the 0th and 1st elements) from the input list.\n\n3. The code enters a loop that iterates through the remaining coordinates (from index 2 to n-1).\n\n4. For each coordinate (x, y) in the loop, it checks whether the condition (y - y1) * (x - x2) != (y - y2) * (x - x1) is satisfied. This condition is checking if the slopes between the current point and the first two points are equal. If this condition is not met for any point, the method returns False, indicating that the points do not lie on a straight line.\n\n5. If the loop completes without finding any point that breaks the condition, the method returns True, indicating that all the points form a straight line.\n\nThis code is implementing a mathematical concept to check if a set of points is collinear (lies on a straight line) by comparing the slopes between the first two points and all other points. If all slopes are equal, the points are collinear; otherwise, they are not.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def checkStraightLine(self, coordinates: List[List[int]]) -> bool:\n n = len(coordinates)\n\n x1, y1 = coordinates[0]\n x2, y2 = coordinates[1]\n\n for i in range(2, n):\n x, y = coordinates[i]\n\n if (y - y1) * (x - x2) != (y - y2) * (x - x1):\n return False\n\n return True\n``` | 1 | Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character.
Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the **maximum** number of students that can take the exam together without any cheating being possible..
Students must be placed in seats in good condition.
**Example 1:**
**Input:** seats = \[\[ "# ", ". ", "# ", "# ", ". ", "# "\],
\[ ". ", "# ", "# ", "# ", "# ", ". "\],
\[ "# ", ". ", "# ", "# ", ". ", "# "\]\]
**Output:** 4
**Explanation:** Teacher can place 4 students in available seats so they don't cheat on the exam.
**Example 2:**
**Input:** seats = \[\[ ". ", "# "\],
\[ "# ", "# "\],
\[ "# ", ". "\],
\[ "# ", "# "\],
\[ ". ", "# "\]\]
**Output:** 3
**Explanation:** Place all students in available seats.
**Example 3:**
**Input:** seats = \[\[ "# ", ". ", "**.** ", ". ", "# "\],
\[ "**.** ", "# ", "**.** ", "# ", "**.** "\],
\[ "**.** ", ". ", "# ", ". ", "**.** "\],
\[ "**.** ", "# ", "**.** ", "# ", "**.** "\],
\[ "# ", ". ", "**.** ", ". ", "# "\]\]
**Output:** 10
**Explanation:** Place students in available seats in column 1, 3 and 5.
**Constraints:**
* `seats` contains only characters `'.' and``'#'.`
* `m == seats.length`
* `n == seats[i].length`
* `1 <= m <= 8`
* `1 <= n <= 8` | If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity. |
Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand | check-if-it-is-a-straight-line | 1 | 1 | # !! BIG ANNOUNCEMENT !!\r\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. This is only for the first 10,000 Subscribers. **DON\'T FORGET** to Subscribe\r\n\r\n# Search \uD83D\uDC49 `Tech Wired Leetcode` to Subscribe\r\n\r\n\r\n# or\r\n\r\n# Click the Link in my Profile\r\n\r\n# Intuition:\r\nTo determine if a set of points lies on a straight line, we can check if the slopes between any two consecutive points are equal. If all the slopes are equal, then the points lie on a straight line; otherwise, they do not.\r\n\r\n# Approach:\r\n\r\n- Extract the coordinates of the first two points (x0, y0) and (x1, y1) from the input.\r\n- Iterate through the remaining points from the third point onwards.\r\n- For each point (x, y) in the iteration:\r\n- Calculate the slope between (x0, y0) and (x1, y1) as (x1 - x0) / (y1 - y0).\r\n- Calculate the slope between (x0, y0) and the current point (x, y) as (x - x0) / (y - y0).\r\n- If the two slopes are not equal, return False, indicating that the points do not form a straight line.\r\n- If all the slopes are equal, return True, indicating that the points form a straight line.\r\n- By checking the equality of the slopes, we can determine whether all the points lie on a straight line or not.\r\n\r\n\r\n```Python []\r\nclass Solution:\r\n def checkStraightLine(self, coordinates):\r\n x0, y0 = coordinates[0]\r\n x1, y1 = coordinates[1]\r\n\r\n for i in range(2, len(coordinates)):\r\n x, y = coordinates[i]\r\n if (x - x0) * (y1 - y0) != (y - y0) * (x1 - x0):\r\n return False\r\n\r\n return True\r\n\r\n```\r\n```Java []\r\nclass Solution {\r\n public boolean checkStraightLine(int[][] coordinates) {\r\n int x0 = coordinates[0][0];\r\n int y0 = coordinates[0][1];\r\n int x1 = coordinates[1][0];\r\n int y1 = coordinates[1][1];\r\n \r\n for (int i = 2; i < coordinates.length; i++) {\r\n int x = coordinates[i][0];\r\n int y = coordinates[i][1];\r\n if ((x - x0) * (y1 - y0) != (y - y0) * (x1 - x0)) {\r\n return false;\r\n }\r\n }\r\n \r\n return true;\r\n }\r\n}\r\n\r\n```\r\n```C++ []\r\nclass Solution {\r\npublic:\r\n bool checkStraightLine(vector<vector<int>>& coordinates) {\r\n int x0 = coordinates[0][0];\r\n int y0 = coordinates[0][1];\r\n int x1 = coordinates[1][0];\r\n int y1 = coordinates[1][1];\r\n \r\n for (int i = 2; i < coordinates.size(); i++) {\r\n int x = coordinates[i][0];\r\n int y = coordinates[i][1];\r\n if ((x - x0) * (y1 - y0) != (y - y0) * (x1 - x0)) {\r\n return false;\r\n }\r\n }\r\n \r\n return true;\r\n }\r\n};\r\n\r\n```\r\n# An Upvote will be encouraging \uD83D\uDC4D | 44 | You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane.
**Example 1:**
**Input:** coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\]
**Output:** true
**Example 2:**
**Input:** coordinates = \[\[1,1\],\[2,2\],\[3,4\],\[4,5\],\[5,6\],\[7,7\]\]
**Output:** false
**Constraints:**
* `2 <= coordinates.length <= 1000`
* `coordinates[i].length == 2`
* `-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4`
* `coordinates` contains no duplicate point. | If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value. |
Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand | check-if-it-is-a-straight-line | 1 | 1 | # !! BIG ANNOUNCEMENT !!\r\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. This is only for the first 10,000 Subscribers. **DON\'T FORGET** to Subscribe\r\n\r\n# Search \uD83D\uDC49 `Tech Wired Leetcode` to Subscribe\r\n\r\n\r\n# or\r\n\r\n# Click the Link in my Profile\r\n\r\n# Intuition:\r\nTo determine if a set of points lies on a straight line, we can check if the slopes between any two consecutive points are equal. If all the slopes are equal, then the points lie on a straight line; otherwise, they do not.\r\n\r\n# Approach:\r\n\r\n- Extract the coordinates of the first two points (x0, y0) and (x1, y1) from the input.\r\n- Iterate through the remaining points from the third point onwards.\r\n- For each point (x, y) in the iteration:\r\n- Calculate the slope between (x0, y0) and (x1, y1) as (x1 - x0) / (y1 - y0).\r\n- Calculate the slope between (x0, y0) and the current point (x, y) as (x - x0) / (y - y0).\r\n- If the two slopes are not equal, return False, indicating that the points do not form a straight line.\r\n- If all the slopes are equal, return True, indicating that the points form a straight line.\r\n- By checking the equality of the slopes, we can determine whether all the points lie on a straight line or not.\r\n\r\n\r\n```Python []\r\nclass Solution:\r\n def checkStraightLine(self, coordinates):\r\n x0, y0 = coordinates[0]\r\n x1, y1 = coordinates[1]\r\n\r\n for i in range(2, len(coordinates)):\r\n x, y = coordinates[i]\r\n if (x - x0) * (y1 - y0) != (y - y0) * (x1 - x0):\r\n return False\r\n\r\n return True\r\n\r\n```\r\n```Java []\r\nclass Solution {\r\n public boolean checkStraightLine(int[][] coordinates) {\r\n int x0 = coordinates[0][0];\r\n int y0 = coordinates[0][1];\r\n int x1 = coordinates[1][0];\r\n int y1 = coordinates[1][1];\r\n \r\n for (int i = 2; i < coordinates.length; i++) {\r\n int x = coordinates[i][0];\r\n int y = coordinates[i][1];\r\n if ((x - x0) * (y1 - y0) != (y - y0) * (x1 - x0)) {\r\n return false;\r\n }\r\n }\r\n \r\n return true;\r\n }\r\n}\r\n\r\n```\r\n```C++ []\r\nclass Solution {\r\npublic:\r\n bool checkStraightLine(vector<vector<int>>& coordinates) {\r\n int x0 = coordinates[0][0];\r\n int y0 = coordinates[0][1];\r\n int x1 = coordinates[1][0];\r\n int y1 = coordinates[1][1];\r\n \r\n for (int i = 2; i < coordinates.size(); i++) {\r\n int x = coordinates[i][0];\r\n int y = coordinates[i][1];\r\n if ((x - x0) * (y1 - y0) != (y - y0) * (x1 - x0)) {\r\n return false;\r\n }\r\n }\r\n \r\n return true;\r\n }\r\n};\r\n\r\n```\r\n# An Upvote will be encouraging \uD83D\uDC4D | 44 | Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character.
Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the **maximum** number of students that can take the exam together without any cheating being possible..
Students must be placed in seats in good condition.
**Example 1:**
**Input:** seats = \[\[ "# ", ". ", "# ", "# ", ". ", "# "\],
\[ ". ", "# ", "# ", "# ", "# ", ". "\],
\[ "# ", ". ", "# ", "# ", ". ", "# "\]\]
**Output:** 4
**Explanation:** Teacher can place 4 students in available seats so they don't cheat on the exam.
**Example 2:**
**Input:** seats = \[\[ ". ", "# "\],
\[ "# ", "# "\],
\[ "# ", ". "\],
\[ "# ", "# "\],
\[ ". ", "# "\]\]
**Output:** 3
**Explanation:** Place all students in available seats.
**Example 3:**
**Input:** seats = \[\[ "# ", ". ", "**.** ", ". ", "# "\],
\[ "**.** ", "# ", "**.** ", "# ", "**.** "\],
\[ "**.** ", ". ", "# ", ". ", "**.** "\],
\[ "**.** ", "# ", "**.** ", "# ", "**.** "\],
\[ "# ", ". ", "**.** ", ". ", "# "\]\]
**Output:** 10
**Explanation:** Place students in available seats in column 1, 3 and 5.
**Constraints:**
* `seats` contains only characters `'.' and``'#'.`
* `m == seats.length`
* `n == seats[i].length`
* `1 <= m <= 8`
* `1 <= n <= 8` | If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity. |
[Java/Python 3] check slopes, short code w/ explanation and analysis. | check-if-it-is-a-straight-line | 1 | 1 | The slope for a line through any 2 points `(x0, y0)` and `(x1, y1)` is `(y1 - y0) / (x1 - x0)`; Therefore, for any given 3 points (denote the 3rd point as `(x, y)`), if they are in a straight line, the slopes of the lines from the 3rd point to the 2nd point and the 2nd point to the 1st point must be equal:\n```\n(y - y1) / (x - x1) = (y1 - y0) / (x1 - x0)\n```\nIn order to avoid being divided by 0, use multiplication form:\n```\n(x1 - x0) * (y - y1) = (x - x1) * (y1 - y0) =>\ndx * (y - y1) = dy * (x - x1), where dx = x1 - x0 and dy = y1 - y0\n```\n\nNow imagine connecting the 2nd points respectively with others one by one, Check if all of the slopes are equal.\n\n```\n public boolean checkStraightLine(int[][] coordinates) {\n int x0 = coordinates[0][0], y0 = coordinates[0][1], \n x1 = coordinates[1][0], y1 = coordinates[1][1];\n int dx = x1 - x0, dy = y1 - y0;\n for (int[] co : coordinates) {\n int x = co[0], y = co[1];\n if (dx * (y - y1) != dy * (x - x1))\n return false;\n }\n return true;\n }\n```\n```\n def checkStraightLine(self, coordinates: List[List[int]]) -> bool:\n (x0, y0), (x1, y1) = coordinates[: 2]\n for x, y in coordinates:\n if (x1 - x0) * (y - y1) != (x - x1) * (y1 - y0):\n return False\n return True\n```\nor simpler:\n```\n def checkStraightLine(self, coordinates: List[List[int]]) -> bool:\n (x0, y0), (x1, y1) = coordinates[: 2]\n return all((x1 - x0) * (y - y1) == (x - x1) * (y1 - y0) for x, y in coordinates)\n```\n\n**Analysis**\n\nTime: O(n), space: O(1), where n = coordinates.length. | 306 | You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane.
**Example 1:**
**Input:** coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\]
**Output:** true
**Example 2:**
**Input:** coordinates = \[\[1,1\],\[2,2\],\[3,4\],\[4,5\],\[5,6\],\[7,7\]\]
**Output:** false
**Constraints:**
* `2 <= coordinates.length <= 1000`
* `coordinates[i].length == 2`
* `-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4`
* `coordinates` contains no duplicate point. | If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value. |
[Java/Python 3] check slopes, short code w/ explanation and analysis. | check-if-it-is-a-straight-line | 1 | 1 | The slope for a line through any 2 points `(x0, y0)` and `(x1, y1)` is `(y1 - y0) / (x1 - x0)`; Therefore, for any given 3 points (denote the 3rd point as `(x, y)`), if they are in a straight line, the slopes of the lines from the 3rd point to the 2nd point and the 2nd point to the 1st point must be equal:\n```\n(y - y1) / (x - x1) = (y1 - y0) / (x1 - x0)\n```\nIn order to avoid being divided by 0, use multiplication form:\n```\n(x1 - x0) * (y - y1) = (x - x1) * (y1 - y0) =>\ndx * (y - y1) = dy * (x - x1), where dx = x1 - x0 and dy = y1 - y0\n```\n\nNow imagine connecting the 2nd points respectively with others one by one, Check if all of the slopes are equal.\n\n```\n public boolean checkStraightLine(int[][] coordinates) {\n int x0 = coordinates[0][0], y0 = coordinates[0][1], \n x1 = coordinates[1][0], y1 = coordinates[1][1];\n int dx = x1 - x0, dy = y1 - y0;\n for (int[] co : coordinates) {\n int x = co[0], y = co[1];\n if (dx * (y - y1) != dy * (x - x1))\n return false;\n }\n return true;\n }\n```\n```\n def checkStraightLine(self, coordinates: List[List[int]]) -> bool:\n (x0, y0), (x1, y1) = coordinates[: 2]\n for x, y in coordinates:\n if (x1 - x0) * (y - y1) != (x - x1) * (y1 - y0):\n return False\n return True\n```\nor simpler:\n```\n def checkStraightLine(self, coordinates: List[List[int]]) -> bool:\n (x0, y0), (x1, y1) = coordinates[: 2]\n return all((x1 - x0) * (y - y1) == (x - x1) * (y1 - y0) for x, y in coordinates)\n```\n\n**Analysis**\n\nTime: O(n), space: O(1), where n = coordinates.length. | 306 | Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character.
Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the **maximum** number of students that can take the exam together without any cheating being possible..
Students must be placed in seats in good condition.
**Example 1:**
**Input:** seats = \[\[ "# ", ". ", "# ", "# ", ". ", "# "\],
\[ ". ", "# ", "# ", "# ", "# ", ". "\],
\[ "# ", ". ", "# ", "# ", ". ", "# "\]\]
**Output:** 4
**Explanation:** Teacher can place 4 students in available seats so they don't cheat on the exam.
**Example 2:**
**Input:** seats = \[\[ ". ", "# "\],
\[ "# ", "# "\],
\[ "# ", ". "\],
\[ "# ", "# "\],
\[ ". ", "# "\]\]
**Output:** 3
**Explanation:** Place all students in available seats.
**Example 3:**
**Input:** seats = \[\[ "# ", ". ", "**.** ", ". ", "# "\],
\[ "**.** ", "# ", "**.** ", "# ", "**.** "\],
\[ "**.** ", ". ", "# ", ". ", "**.** "\],
\[ "**.** ", "# ", "**.** ", "# ", "**.** "\],
\[ "# ", ". ", "**.** ", ". ", "# "\]\]
**Output:** 10
**Explanation:** Place students in available seats in column 1, 3 and 5.
**Constraints:**
* `seats` contains only characters `'.' and``'#'.`
* `m == seats.length`
* `n == seats[i].length`
* `1 <= m <= 8`
* `1 <= n <= 8` | If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity. |
Python Elegant & Short | 3-Lines | check-if-it-is-a-straight-line | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def checkStraightLine(self, coordinates: List[List[int]]) -> bool:\n x0, y0 = coordinates.pop()\n x1, y1 = coordinates.pop()\n return all((x1 - x0) * (y - y1) == (x - x1) * (y1 - y0) for x, y in coordinates)\n``` | 6 | You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane.
**Example 1:**
**Input:** coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\]
**Output:** true
**Example 2:**
**Input:** coordinates = \[\[1,1\],\[2,2\],\[3,4\],\[4,5\],\[5,6\],\[7,7\]\]
**Output:** false
**Constraints:**
* `2 <= coordinates.length <= 1000`
* `coordinates[i].length == 2`
* `-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4`
* `coordinates` contains no duplicate point. | If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value. |
Python Elegant & Short | 3-Lines | check-if-it-is-a-straight-line | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def checkStraightLine(self, coordinates: List[List[int]]) -> bool:\n x0, y0 = coordinates.pop()\n x1, y1 = coordinates.pop()\n return all((x1 - x0) * (y - y1) == (x - x1) * (y1 - y0) for x, y in coordinates)\n``` | 6 | Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character.
Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the **maximum** number of students that can take the exam together without any cheating being possible..
Students must be placed in seats in good condition.
**Example 1:**
**Input:** seats = \[\[ "# ", ". ", "# ", "# ", ". ", "# "\],
\[ ". ", "# ", "# ", "# ", "# ", ". "\],
\[ "# ", ". ", "# ", "# ", ". ", "# "\]\]
**Output:** 4
**Explanation:** Teacher can place 4 students in available seats so they don't cheat on the exam.
**Example 2:**
**Input:** seats = \[\[ ". ", "# "\],
\[ "# ", "# "\],
\[ "# ", ". "\],
\[ "# ", "# "\],
\[ ". ", "# "\]\]
**Output:** 3
**Explanation:** Place all students in available seats.
**Example 3:**
**Input:** seats = \[\[ "# ", ". ", "**.** ", ". ", "# "\],
\[ "**.** ", "# ", "**.** ", "# ", "**.** "\],
\[ "**.** ", ". ", "# ", ". ", "**.** "\],
\[ "**.** ", "# ", "**.** ", "# ", "**.** "\],
\[ "# ", ". ", "**.** ", ". ", "# "\]\]
**Output:** 10
**Explanation:** Place students in available seats in column 1, 3 and 5.
**Constraints:**
* `seats` contains only characters `'.' and``'#'.`
* `m == seats.length`
* `n == seats[i].length`
* `1 <= m <= 8`
* `1 <= n <= 8` | If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity. |
[Java] [Python3] [CPP] | Simple code with explanation | 100% fast | O(1) space | check-if-it-is-a-straight-line | 1 | 1 | \n**The point is if we take points p1(x, y), p2(x1, y1), p3(x3, y3), slopes of any two pairs is same then p1, p2, p3 lies on same line.\n slope from p1 and p2 is y - y1 / x - x1\n slope from p2 and p3 is y2 - y1 / x2 - x1\nif these two slopes equal, then p1, p2, p3 lies on same line.**\n\n**IF YOU HAVE ANY DOUBTS, FEEL FREE TO ASK**\n**IF YOU UNDERSTAND, DON\'T FORGET TO UPVOTE**\n\n\n\n```\nJAVA:- \n\nclass Solution {\n public boolean onLine(int[] p1, int[] p2, int[] p3){\n int x = p1[0], y = p1[1], x1 = p2[0], y1 = p2[1], x2 = p3[0], y2 = p3[1];\n return ((y - y1) * (x2 - x1) == (y2 - y1) * (x - x1));\n }\n public boolean checkStraightLine(int[][] coordinates) {\n // base case:- there are only two points, return true\n // otherwise, check each point lies on line using above equation.\n\t\t\n for(int i=2;i<coordinates.length;i++){\n if(!onLine(coordinates[i], coordinates[0], coordinates[1]))\n return false;\n }\n return true;\n }\n}\n\n\nPython3:-\n\nclass Solution:\n def checkStraightLine(self, coordinates: List[List[int]]) -> bool:\n (x1, y1), (x2, y2) = coordinates[:2]\n for i in range(2, len(coordinates)):\n (x, y) = coordinates[i]\n if((y2 - y1) * (x1 - x) != (y1 - y) * (x2 - x1)):\n return False\n return True\t\t\n\nCPP:-\n\u200Bclass Solution {\npublic:\n bool checkStraightLine(vector<vector<int>>& coordinates) {\n if(coordinates.size() <= 2) return true;\n int x1 = coordinates[0][0];\n int y1 = coordinates[0][1];\n int x2 = coordinates[1][0];\n int y2 = coordinates[1][1];\n for(int i=2;i<coordinates.size();i++){\n int x = coordinates[i][0];\n int y = coordinates[i][1];\n if((y2 - y1) * (x1 - x) != (y1 - y) * (x2 - x1))\n return false;\n }\n return true;\n }\n};\n```\n | 205 | You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane.
**Example 1:**
**Input:** coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\]
**Output:** true
**Example 2:**
**Input:** coordinates = \[\[1,1\],\[2,2\],\[3,4\],\[4,5\],\[5,6\],\[7,7\]\]
**Output:** false
**Constraints:**
* `2 <= coordinates.length <= 1000`
* `coordinates[i].length == 2`
* `-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4`
* `coordinates` contains no duplicate point. | If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value. |
[Java] [Python3] [CPP] | Simple code with explanation | 100% fast | O(1) space | check-if-it-is-a-straight-line | 1 | 1 | \n**The point is if we take points p1(x, y), p2(x1, y1), p3(x3, y3), slopes of any two pairs is same then p1, p2, p3 lies on same line.\n slope from p1 and p2 is y - y1 / x - x1\n slope from p2 and p3 is y2 - y1 / x2 - x1\nif these two slopes equal, then p1, p2, p3 lies on same line.**\n\n**IF YOU HAVE ANY DOUBTS, FEEL FREE TO ASK**\n**IF YOU UNDERSTAND, DON\'T FORGET TO UPVOTE**\n\n\n\n```\nJAVA:- \n\nclass Solution {\n public boolean onLine(int[] p1, int[] p2, int[] p3){\n int x = p1[0], y = p1[1], x1 = p2[0], y1 = p2[1], x2 = p3[0], y2 = p3[1];\n return ((y - y1) * (x2 - x1) == (y2 - y1) * (x - x1));\n }\n public boolean checkStraightLine(int[][] coordinates) {\n // base case:- there are only two points, return true\n // otherwise, check each point lies on line using above equation.\n\t\t\n for(int i=2;i<coordinates.length;i++){\n if(!onLine(coordinates[i], coordinates[0], coordinates[1]))\n return false;\n }\n return true;\n }\n}\n\n\nPython3:-\n\nclass Solution:\n def checkStraightLine(self, coordinates: List[List[int]]) -> bool:\n (x1, y1), (x2, y2) = coordinates[:2]\n for i in range(2, len(coordinates)):\n (x, y) = coordinates[i]\n if((y2 - y1) * (x1 - x) != (y1 - y) * (x2 - x1)):\n return False\n return True\t\t\n\nCPP:-\n\u200Bclass Solution {\npublic:\n bool checkStraightLine(vector<vector<int>>& coordinates) {\n if(coordinates.size() <= 2) return true;\n int x1 = coordinates[0][0];\n int y1 = coordinates[0][1];\n int x2 = coordinates[1][0];\n int y2 = coordinates[1][1];\n for(int i=2;i<coordinates.size();i++){\n int x = coordinates[i][0];\n int y = coordinates[i][1];\n if((y2 - y1) * (x1 - x) != (y1 - y) * (x2 - x1))\n return false;\n }\n return true;\n }\n};\n```\n | 205 | Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character.
Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the **maximum** number of students that can take the exam together without any cheating being possible..
Students must be placed in seats in good condition.
**Example 1:**
**Input:** seats = \[\[ "# ", ". ", "# ", "# ", ". ", "# "\],
\[ ". ", "# ", "# ", "# ", "# ", ". "\],
\[ "# ", ". ", "# ", "# ", ". ", "# "\]\]
**Output:** 4
**Explanation:** Teacher can place 4 students in available seats so they don't cheat on the exam.
**Example 2:**
**Input:** seats = \[\[ ". ", "# "\],
\[ "# ", "# "\],
\[ "# ", ". "\],
\[ "# ", "# "\],
\[ ". ", "# "\]\]
**Output:** 3
**Explanation:** Place all students in available seats.
**Example 3:**
**Input:** seats = \[\[ "# ", ". ", "**.** ", ". ", "# "\],
\[ "**.** ", "# ", "**.** ", "# ", "**.** "\],
\[ "**.** ", ". ", "# ", ". ", "**.** "\],
\[ "**.** ", "# ", "**.** ", "# ", "**.** "\],
\[ "# ", ". ", "**.** ", ". ", "# "\]\]
**Output:** 10
**Explanation:** Place students in available seats in column 1, 3 and 5.
**Constraints:**
* `seats` contains only characters `'.' and``'#'.`
* `m == seats.length`
* `n == seats[i].length`
* `1 <= m <= 8`
* `1 <= n <= 8` | If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity. |
2 passes, Python trie solution (no sorting) | remove-sub-folders-from-the-filesystem | 0 | 1 | \n```\nclass TrieNode:\n def __init__(self):\n self.children = collections.defaultdict(TrieNode)\n self.end = False\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n\n def insert(self, path):\n curr = self.root\n for i in range(len(path)):\n curr = curr.children[path[i]]\n curr.end = True\n\n\n def search(self, path):\n curr = self.root\n for i in range(len(path)):\n curr = curr.children[path[i]]\n if curr.end and i != len(path) - 1:\n return False\n\n return True\n\nclass Solution:\n def removeSubfolders(self, folder: List[str]) -> List[str]:\n trie = Trie()\n res = []\n\n for f in folder:\n trie.insert(f.split("/"))\n \n for f in folder:\n if trie.search(f.split("/")):\n res.append(f)\n\n return res\n``` | 0 | Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**.
If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of it.
The format of a path is one or more concatenated strings of the form: `'/'` followed by one or more lowercase English letters.
* For example, `"/leetcode "` and `"/leetcode/problems "` are valid paths while an empty string and `"/ "` are not.
**Example 1:**
**Input:** folder = \[ "/a ", "/a/b ", "/c/d ", "/c/d/e ", "/c/f "\]
**Output:** \[ "/a ", "/c/d ", "/c/f "\]
**Explanation:** Folders "/a/b " is a subfolder of "/a " and "/c/d/e " is inside of folder "/c/d " in our filesystem.
**Example 2:**
**Input:** folder = \[ "/a ", "/a/b/c ", "/a/b/d "\]
**Output:** \[ "/a "\]
**Explanation:** Folders "/a/b/c " and "/a/b/d " will be removed because they are subfolders of "/a ".
**Example 3:**
**Input:** folder = \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Output:** \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Constraints:**
* `1 <= folder.length <= 4 * 104`
* `2 <= folder[i].length <= 100`
* `folder[i]` contains only lowercase letters and `'/'`.
* `folder[i]` always starts with the character `'/'`.
* Each folder name is **unique**. | Use divide and conquer technique. Divide the query rectangle into 4 rectangles. Use recursion to continue with the rectangles that has ships only. |
Python trie backtracking solution | remove-sub-folders-from-the-filesystem | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nConsider the folder names and build a trie (prefix tree) out of it. Traverse the trie to find the valid paths only\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Split by `/` and consider the characters only\n- Build a prefix tree out of it\n- Find the paths for every branch encounters the first valid path\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n * m)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass TreeNode:\n def __init__(self):\n self.children = {}\n self.is_word = False\n\nclass Solution:\n def removeSubfolders(self, folder: List[str]) -> List[str]:\n # ["/a","/a/b","/c/d","/c/d/e","/c/f"]\n # /a\n # /a/b\n\n node = TreeNode()\n res = []\n\n for i in folder:\n cur = node\n folders = i.strip("/").split("/")\n\n for folder in folders:\n if folder not in cur.children:\n cur.children[folder] = TreeNode()\n cur = cur.children[folder]\n cur.is_word = True\n \n self.find_paths(node.children, res, None)\n \n return res\n \n def find_paths(self, nodes, res, prev_key):\n for key, item in nodes.items():\n valid_key = f"{prev_key}/{key}" if prev_key else f"/{key}"\n if item.is_word:\n res.append(valid_key)\n continue\n self.find_paths(item.children, res, valid_key)\n``` | 0 | Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**.
If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of it.
The format of a path is one or more concatenated strings of the form: `'/'` followed by one or more lowercase English letters.
* For example, `"/leetcode "` and `"/leetcode/problems "` are valid paths while an empty string and `"/ "` are not.
**Example 1:**
**Input:** folder = \[ "/a ", "/a/b ", "/c/d ", "/c/d/e ", "/c/f "\]
**Output:** \[ "/a ", "/c/d ", "/c/f "\]
**Explanation:** Folders "/a/b " is a subfolder of "/a " and "/c/d/e " is inside of folder "/c/d " in our filesystem.
**Example 2:**
**Input:** folder = \[ "/a ", "/a/b/c ", "/a/b/d "\]
**Output:** \[ "/a "\]
**Explanation:** Folders "/a/b/c " and "/a/b/d " will be removed because they are subfolders of "/a ".
**Example 3:**
**Input:** folder = \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Output:** \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Constraints:**
* `1 <= folder.length <= 4 * 104`
* `2 <= folder[i].length <= 100`
* `folder[i]` contains only lowercase letters and `'/'`.
* `folder[i]` always starts with the character `'/'`.
* Each folder name is **unique**. | Use divide and conquer technique. Divide the query rectangle into 4 rectangles. Use recursion to continue with the rectangles that has ships only. |
very simple solution using only one for | remove-sub-folders-from-the-filesystem | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def removeSubfolders(self, folder: List[str]) -> List[str]:\n folder.sort()\n get = folder[0]+\'/\'\n ans = [folder[0]]\n for i in range(1, len(folder)):\n if not folder[i].startswith(get):\n ans.append(folder[i])\n get = folder[i]+\'/\'\n return ans\n``` | 0 | Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**.
If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of it.
The format of a path is one or more concatenated strings of the form: `'/'` followed by one or more lowercase English letters.
* For example, `"/leetcode "` and `"/leetcode/problems "` are valid paths while an empty string and `"/ "` are not.
**Example 1:**
**Input:** folder = \[ "/a ", "/a/b ", "/c/d ", "/c/d/e ", "/c/f "\]
**Output:** \[ "/a ", "/c/d ", "/c/f "\]
**Explanation:** Folders "/a/b " is a subfolder of "/a " and "/c/d/e " is inside of folder "/c/d " in our filesystem.
**Example 2:**
**Input:** folder = \[ "/a ", "/a/b/c ", "/a/b/d "\]
**Output:** \[ "/a "\]
**Explanation:** Folders "/a/b/c " and "/a/b/d " will be removed because they are subfolders of "/a ".
**Example 3:**
**Input:** folder = \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Output:** \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Constraints:**
* `1 <= folder.length <= 4 * 104`
* `2 <= folder[i].length <= 100`
* `folder[i]` contains only lowercase letters and `'/'`.
* `folder[i]` always starts with the character `'/'`.
* Each folder name is **unique**. | Use divide and conquer technique. Divide the query rectangle into 4 rectangles. Use recursion to continue with the rectangles that has ships only. |
Easy to understand Python3 solution | remove-sub-folders-from-the-filesystem | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def removeSubfolders(self, folder: List[str]) -> List[str]:\n folder.sort()\n\n i = 0\n while i < len(folder) - 1:\n if folder[i] + "/" in folder[i+1][:len(folder[i])+1]:\n del folder[i+1]\n else:\n i += 1\n \n return folder\n \n``` | 0 | Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**.
If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of it.
The format of a path is one or more concatenated strings of the form: `'/'` followed by one or more lowercase English letters.
* For example, `"/leetcode "` and `"/leetcode/problems "` are valid paths while an empty string and `"/ "` are not.
**Example 1:**
**Input:** folder = \[ "/a ", "/a/b ", "/c/d ", "/c/d/e ", "/c/f "\]
**Output:** \[ "/a ", "/c/d ", "/c/f "\]
**Explanation:** Folders "/a/b " is a subfolder of "/a " and "/c/d/e " is inside of folder "/c/d " in our filesystem.
**Example 2:**
**Input:** folder = \[ "/a ", "/a/b/c ", "/a/b/d "\]
**Output:** \[ "/a "\]
**Explanation:** Folders "/a/b/c " and "/a/b/d " will be removed because they are subfolders of "/a ".
**Example 3:**
**Input:** folder = \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Output:** \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Constraints:**
* `1 <= folder.length <= 4 * 104`
* `2 <= folder[i].length <= 100`
* `folder[i]` contains only lowercase letters and `'/'`.
* `folder[i]` always starts with the character `'/'`.
* Each folder name is **unique**. | Use divide and conquer technique. Divide the query rectangle into 4 rectangles. Use recursion to continue with the rectangles that has ships only. |
Trie, DFS | remove-sub-folders-from-the-filesystem | 0 | 1 | \n# Code\n```\nclass Trie:\n\n def __init__(self):\n self.dic = dict()\n \n def add(self, word):\n l = word.split(\'/\')\n cur = self.dic\n for ch in l:\n if ch not in cur:\n cur[ch] = {}\n cur = cur[ch]\n cur[\'*\'] = \'\'\n \n def clean(self, dic):\n ks = list(dic.keys())\n for ch in ks:\n if ch != \'*\':\n del dic[ch]\n return\n\n def remove(self, dic):\n if \'*\' in dic:\n self.clean(dic)\n for ch in dic:\n self.remove(dic[ch])\n return\n\n def traverse(self, dic):\n if dic == \'\':\n return [\'\']\n ret = []\n for ch in dic:\n for w in self.traverse(dic[ch]):\n if ch == \'*\':\n ret.append(w)\n else:\n ret.append(\'/\'.join([ch, w]))\n return ret\n\n\nclass Solution:\n def removeSubfolders(self, folder: List[str]) -> List[str]:\n trie = Trie()\n for p in folder:\n trie.add(p)\n for ch in trie.dic:\n trie.remove(trie.dic[ch])\n \n return [w[:-1] for w in trie.traverse(trie.dic)]\n \n``` | 0 | Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**.
If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of it.
The format of a path is one or more concatenated strings of the form: `'/'` followed by one or more lowercase English letters.
* For example, `"/leetcode "` and `"/leetcode/problems "` are valid paths while an empty string and `"/ "` are not.
**Example 1:**
**Input:** folder = \[ "/a ", "/a/b ", "/c/d ", "/c/d/e ", "/c/f "\]
**Output:** \[ "/a ", "/c/d ", "/c/f "\]
**Explanation:** Folders "/a/b " is a subfolder of "/a " and "/c/d/e " is inside of folder "/c/d " in our filesystem.
**Example 2:**
**Input:** folder = \[ "/a ", "/a/b/c ", "/a/b/d "\]
**Output:** \[ "/a "\]
**Explanation:** Folders "/a/b/c " and "/a/b/d " will be removed because they are subfolders of "/a ".
**Example 3:**
**Input:** folder = \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Output:** \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Constraints:**
* `1 <= folder.length <= 4 * 104`
* `2 <= folder[i].length <= 100`
* `folder[i]` contains only lowercase letters and `'/'`.
* `folder[i]` always starts with the character `'/'`.
* Each folder name is **unique**. | Use divide and conquer technique. Divide the query rectangle into 4 rectangles. Use recursion to continue with the rectangles that has ships only. |
[Python3] Good enough | remove-sub-folders-from-the-filesystem | 0 | 1 | ``` Python3 []\nclass Solution:\n def removeSubfolders(self, folder: List[str]) -> List[str]:\n folder.sort(key=lambda x: len(x))\n seen = set()\n final = []\n\n for x in folder:\n for i in range(2, len(x.split(\'/\'))):\n if tuple(x.split(\'/\')[1:i]) in seen:\n break\n else:\n final.append(x)\n seen.add(tuple(x.split(\'/\')[1:]))\n \n return final\n``` | 0 | Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**.
If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of it.
The format of a path is one or more concatenated strings of the form: `'/'` followed by one or more lowercase English letters.
* For example, `"/leetcode "` and `"/leetcode/problems "` are valid paths while an empty string and `"/ "` are not.
**Example 1:**
**Input:** folder = \[ "/a ", "/a/b ", "/c/d ", "/c/d/e ", "/c/f "\]
**Output:** \[ "/a ", "/c/d ", "/c/f "\]
**Explanation:** Folders "/a/b " is a subfolder of "/a " and "/c/d/e " is inside of folder "/c/d " in our filesystem.
**Example 2:**
**Input:** folder = \[ "/a ", "/a/b/c ", "/a/b/d "\]
**Output:** \[ "/a "\]
**Explanation:** Folders "/a/b/c " and "/a/b/d " will be removed because they are subfolders of "/a ".
**Example 3:**
**Input:** folder = \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Output:** \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Constraints:**
* `1 <= folder.length <= 4 * 104`
* `2 <= folder[i].length <= 100`
* `folder[i]` contains only lowercase letters and `'/'`.
* `folder[i]` always starts with the character `'/'`.
* Each folder name is **unique**. | Use divide and conquer technique. Divide the query rectangle into 4 rectangles. Use recursion to continue with the rectangles that has ships only. |
Python simply solution beats 97.80% | remove-sub-folders-from-the-filesystem | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def removeSubfolders(self, folder: List[str]) -> List[str]:\n folder.sort()\n res=[]\n for f in folder:\n if not res or f[0:len(res[-1])+1]!=(res[-1]+\'/\'):\n res.append(f)\n return res\n``` | 0 | Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**.
If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of it.
The format of a path is one or more concatenated strings of the form: `'/'` followed by one or more lowercase English letters.
* For example, `"/leetcode "` and `"/leetcode/problems "` are valid paths while an empty string and `"/ "` are not.
**Example 1:**
**Input:** folder = \[ "/a ", "/a/b ", "/c/d ", "/c/d/e ", "/c/f "\]
**Output:** \[ "/a ", "/c/d ", "/c/f "\]
**Explanation:** Folders "/a/b " is a subfolder of "/a " and "/c/d/e " is inside of folder "/c/d " in our filesystem.
**Example 2:**
**Input:** folder = \[ "/a ", "/a/b/c ", "/a/b/d "\]
**Output:** \[ "/a "\]
**Explanation:** Folders "/a/b/c " and "/a/b/d " will be removed because they are subfolders of "/a ".
**Example 3:**
**Input:** folder = \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Output:** \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Constraints:**
* `1 <= folder.length <= 4 * 104`
* `2 <= folder[i].length <= 100`
* `folder[i]` contains only lowercase letters and `'/'`.
* `folder[i]` always starts with the character `'/'`.
* Each folder name is **unique**. | Use divide and conquer technique. Divide the query rectangle into 4 rectangles. Use recursion to continue with the rectangles that has ships only. |
[Python3] sliding window with explanation | replace-the-substring-for-balanced-string | 0 | 1 | This problem can be split into two small problems:\n1. find out which letters have extra numbers in the string\n2. find out the shortest substring that contains those extra letters\n\nOnce this gets sorted out the solution gonna be pretty straightforward.\nComplexity: time O(n) space O(1)\n\n```\nclass Solution:\n def balancedString(self, s: str) -> int:\n counter = collections.Counter(s)\n n = len(s) // 4\n extras = {}\n for key in counter:\n if counter[key] > n:\n extras[key] = counter[key] - n\n \n if not extras: return 0\n i = 0\n res = len(s)\n for j in range(len(s)):\n if s[j] in extras:\n extras[s[j]] -= 1\n \n while max(extras.values()) <= 0:\n res = min(res, j-i+1)\n if s[i] in extras:\n extras[s[i]] += 1\n i += 1\n \n \n return res\n``` | 11 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** other string of the same length to make_ `s` _**balanced**_. If s is already **balanced**, return `0`.
**Example 1:**
**Input:** s = "QWER "
**Output:** 0
**Explanation:** s is already balanced.
**Example 2:**
**Input:** s = "QQWE "
**Output:** 1
**Explanation:** We need to replace a 'Q' to 'R', so that "RQWE " (or "QRWE ") is balanced.
**Example 3:**
**Input:** s = "QQQW "
**Output:** 2
**Explanation:** We can replace the first "QQ " to "ER ".
**Constraints:**
* `n == s.length`
* `4 <= n <= 105`
* `n` is a multiple of `4`.
* `s` contains only `'Q'`, `'W'`, `'E'`, and `'R'`. | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
[Python3] sliding window with explanation | replace-the-substring-for-balanced-string | 0 | 1 | This problem can be split into two small problems:\n1. find out which letters have extra numbers in the string\n2. find out the shortest substring that contains those extra letters\n\nOnce this gets sorted out the solution gonna be pretty straightforward.\nComplexity: time O(n) space O(1)\n\n```\nclass Solution:\n def balancedString(self, s: str) -> int:\n counter = collections.Counter(s)\n n = len(s) // 4\n extras = {}\n for key in counter:\n if counter[key] > n:\n extras[key] = counter[key] - n\n \n if not extras: return 0\n i = 0\n res = len(s)\n for j in range(len(s)):\n if s[j] in extras:\n extras[s[j]] -= 1\n \n while max(extras.values()) <= 0:\n res = min(res, j-i+1)\n if s[i] in extras:\n extras[s[i]] += 1\n i += 1\n \n \n return res\n``` | 11 | Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the matrix.
**Example 2:**
**Input:** grid = \[\[3,2\],\[1,0\]\]
**Output:** 0
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 100`
* `-100 <= grid[i][j] <= 100`
**Follow up:** Could you find an `O(n + m)` solution? | Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough. |
Python O(n) with no sliding window | replace-the-substring-for-balanced-string | 0 | 1 | ```\n\nfrom collections import Counter,defaultdict\n\nclass Solution:\n def balancedString(self, s: str) -> int:\n extra = Counter(s) - Counter({a: len(s)//4 for a in \'QWER\'})\n if not extra:\n return 0\n \n ans = len(s)\n indices = defaultdict(list)\n for i, a in enumerate(s):\n indices[a].append(i)\n if any(len(indices[k]) < v for k, v in extra.items()):\n continue\n ans = min(ans, i - min(indices[k][-v] for k, v in extra.items()) + 1)\n return ans | 1 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** other string of the same length to make_ `s` _**balanced**_. If s is already **balanced**, return `0`.
**Example 1:**
**Input:** s = "QWER "
**Output:** 0
**Explanation:** s is already balanced.
**Example 2:**
**Input:** s = "QQWE "
**Output:** 1
**Explanation:** We need to replace a 'Q' to 'R', so that "RQWE " (or "QRWE ") is balanced.
**Example 3:**
**Input:** s = "QQQW "
**Output:** 2
**Explanation:** We can replace the first "QQ " to "ER ".
**Constraints:**
* `n == s.length`
* `4 <= n <= 105`
* `n` is a multiple of `4`.
* `s` contains only `'Q'`, `'W'`, `'E'`, and `'R'`. | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
Python O(n) with no sliding window | replace-the-substring-for-balanced-string | 0 | 1 | ```\n\nfrom collections import Counter,defaultdict\n\nclass Solution:\n def balancedString(self, s: str) -> int:\n extra = Counter(s) - Counter({a: len(s)//4 for a in \'QWER\'})\n if not extra:\n return 0\n \n ans = len(s)\n indices = defaultdict(list)\n for i, a in enumerate(s):\n indices[a].append(i)\n if any(len(indices[k]) < v for k, v in extra.items()):\n continue\n ans = min(ans, i - min(indices[k][-v] for k, v in extra.items()) + 1)\n return ans | 1 | Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the matrix.
**Example 2:**
**Input:** grid = \[\[3,2\],\[1,0\]\]
**Output:** 0
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 100`
* `-100 <= grid[i][j] <= 100`
**Follow up:** Could you find an `O(n + m)` solution? | Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough. |
Python 3: Four Queues, Sliding Window | replace-the-substring-for-balanced-string | 0 | 1 | # Intuition\n\nThis took me quite a while to figure out. We can infer the trick is probably some kind of slidng window, but getting the window logic right is tricky.\n\nEventually what I realized was\n* we have `N` elements, divisible by four\n* we want `T = N//4` copies of each character\n* we can change any character(s) in the window to any character - the same or different\n* some characters will have a "surplus," there are more than T copies. Others will have a deficit\n * `totalSurplus == totalDeficit`\n* imagine we deleted all characters in the window, then added arbitrary characters\n * to get exactly `T` characters, we have to delete `count[c] - T` copies of each surplus character\n * since `totalSurplus == totalDeficit`, that means we can convert those surplus characters into the deficient ones\n* **so we want the shortest window that has at least `count[c]-T` copies of each surplus character `c`**\n\n## ASCII Art\n\n```a\nin: WQQWWRWQWWRWREQQWERW N=20, T=5, count[Q]=5, count[W]=9\n |-----| count[R]=4, count[E]=2\n |----| \n |----| surplus chars: W only (surlus = 4)\n |----|\n .....\n\n ^^^^^^^^^^^^^^^^^^\n windows with 4 W\'s\n```\n\nThe only surplus character in this example is `W`; the most surplus characters we can have is 3.\n\nThe answer to this problem is the shortest window with 4 W\'s.\n\n# Approach\n\nIn the ASCII art, once we have 4 W\'s, we do this each time we find a new surplus character:\n* add a new copy to the window\n* pop the last copy from the window\n\nThe earliest first index and latest last index determine the window we need to have the needed number of characters.\n\nTo simplify the logic a bit:\n* I scan across the array, only adding surplus characters to queues\n* using queues makes it easy to push and pop indices\n* using queues also makes it easy to know if we have enough copies, and to know the first copy\'s location: `q[0]`\n\nFurther simplifying the logic\n* have a nonempty queue for every character to avoid no such element issues\n* only push surplus chars to queues\n* start the queues off with guard elements:\n * +N for non-surplus, so our min index over all queues ignores them\n * -N for surplus chars, so if we don\'t have `surplus[c]` actual copies yet, the minimum index is -N. Then `i+1-min(...) > N` so we won\'t update best\n\nGuard elements are a nice algos trick to have. Putting \'+Inf\' in an a decreasing stack, +-N in a queue, etc. can let you skip checking for emptiness. Cleans up loops a bit and prevents bugs when you forget to check.\n\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(N)\n - the max surplus can be 3*N//4, i.e. O(N). So the queue will have O(N) elements in it\n\n# Code\n```\nclass Solution:\n def balancedString(self, s: str) -> int:\n \n\n # if we had cumulative counts of qwer at all indices\n \n # if we swap a window, with counts wq..wr\n # then the remainder is q-wq .. r-wr\n # the target is to get T = S//4\n\n # if not balanced, after some permutation, we have q >= w >= e >= r\n # where q > T > r\n # w and e are unknown\n # we have to convert some majority characters to minority characters\n # countMajority - 2*T of them\n # so we want the smallest window that has at least that surplus for both (if it doesn\'t, we end with a surplus still)\n\n # e.g. for QQQW\n # majority chars: Q, countMajority = 3\n # T = 1\n # delta = 2\n # shortest window with QQ is first two (or second and third)\n\n\n # for QQWW\n # **\n # we have an excess Q and an excess W, so the shortest subarray has to have >= 1 of each\n\n # QxxxxxxQxxxxQQQxxxxxxQ\n # 1 2\n\n # we can have a queue of indices, with length <= surplus\n # when we find a new copy, append the index\n # if the queue has too many now, pop the earliest\n # if all queues with surplus have surplus[char] items, it\'s the min index among them to curr index\n\n N = len(s)\n T = N//4\n counts = Counter(s)\n queues = defaultdict(deque)\n surplus = {c: f-T for c, f in counts.items() if f > T}\n\n if not surplus: return 0\n\n for c in \'QWER\':\n if c in surplus:\n queues[c].append(-N)\n else:\n queues[c].append(N)\n\n\n best = N\n for i, c in enumerate(s):\n if c in surplus:\n q = queues[c]\n q.append(i)\n if len(q) > surplus[c]:\n q.popleft()\n\n # window currently has index i\n # we must go back to the latest (surplus[c]) copy of each surplus char to make it work\n # > +N and -N guard elements mean we don\'t have to test for empty\n best = min(best, i+1-min(q[0] for q in queues.values()))\n\n return best\n``` | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** other string of the same length to make_ `s` _**balanced**_. If s is already **balanced**, return `0`.
**Example 1:**
**Input:** s = "QWER "
**Output:** 0
**Explanation:** s is already balanced.
**Example 2:**
**Input:** s = "QQWE "
**Output:** 1
**Explanation:** We need to replace a 'Q' to 'R', so that "RQWE " (or "QRWE ") is balanced.
**Example 3:**
**Input:** s = "QQQW "
**Output:** 2
**Explanation:** We can replace the first "QQ " to "ER ".
**Constraints:**
* `n == s.length`
* `4 <= n <= 105`
* `n` is a multiple of `4`.
* `s` contains only `'Q'`, `'W'`, `'E'`, and `'R'`. | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
Python 3: Four Queues, Sliding Window | replace-the-substring-for-balanced-string | 0 | 1 | # Intuition\n\nThis took me quite a while to figure out. We can infer the trick is probably some kind of slidng window, but getting the window logic right is tricky.\n\nEventually what I realized was\n* we have `N` elements, divisible by four\n* we want `T = N//4` copies of each character\n* we can change any character(s) in the window to any character - the same or different\n* some characters will have a "surplus," there are more than T copies. Others will have a deficit\n * `totalSurplus == totalDeficit`\n* imagine we deleted all characters in the window, then added arbitrary characters\n * to get exactly `T` characters, we have to delete `count[c] - T` copies of each surplus character\n * since `totalSurplus == totalDeficit`, that means we can convert those surplus characters into the deficient ones\n* **so we want the shortest window that has at least `count[c]-T` copies of each surplus character `c`**\n\n## ASCII Art\n\n```a\nin: WQQWWRWQWWRWREQQWERW N=20, T=5, count[Q]=5, count[W]=9\n |-----| count[R]=4, count[E]=2\n |----| \n |----| surplus chars: W only (surlus = 4)\n |----|\n .....\n\n ^^^^^^^^^^^^^^^^^^\n windows with 4 W\'s\n```\n\nThe only surplus character in this example is `W`; the most surplus characters we can have is 3.\n\nThe answer to this problem is the shortest window with 4 W\'s.\n\n# Approach\n\nIn the ASCII art, once we have 4 W\'s, we do this each time we find a new surplus character:\n* add a new copy to the window\n* pop the last copy from the window\n\nThe earliest first index and latest last index determine the window we need to have the needed number of characters.\n\nTo simplify the logic a bit:\n* I scan across the array, only adding surplus characters to queues\n* using queues makes it easy to push and pop indices\n* using queues also makes it easy to know if we have enough copies, and to know the first copy\'s location: `q[0]`\n\nFurther simplifying the logic\n* have a nonempty queue for every character to avoid no such element issues\n* only push surplus chars to queues\n* start the queues off with guard elements:\n * +N for non-surplus, so our min index over all queues ignores them\n * -N for surplus chars, so if we don\'t have `surplus[c]` actual copies yet, the minimum index is -N. Then `i+1-min(...) > N` so we won\'t update best\n\nGuard elements are a nice algos trick to have. Putting \'+Inf\' in an a decreasing stack, +-N in a queue, etc. can let you skip checking for emptiness. Cleans up loops a bit and prevents bugs when you forget to check.\n\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(N)\n - the max surplus can be 3*N//4, i.e. O(N). So the queue will have O(N) elements in it\n\n# Code\n```\nclass Solution:\n def balancedString(self, s: str) -> int:\n \n\n # if we had cumulative counts of qwer at all indices\n \n # if we swap a window, with counts wq..wr\n # then the remainder is q-wq .. r-wr\n # the target is to get T = S//4\n\n # if not balanced, after some permutation, we have q >= w >= e >= r\n # where q > T > r\n # w and e are unknown\n # we have to convert some majority characters to minority characters\n # countMajority - 2*T of them\n # so we want the smallest window that has at least that surplus for both (if it doesn\'t, we end with a surplus still)\n\n # e.g. for QQQW\n # majority chars: Q, countMajority = 3\n # T = 1\n # delta = 2\n # shortest window with QQ is first two (or second and third)\n\n\n # for QQWW\n # **\n # we have an excess Q and an excess W, so the shortest subarray has to have >= 1 of each\n\n # QxxxxxxQxxxxQQQxxxxxxQ\n # 1 2\n\n # we can have a queue of indices, with length <= surplus\n # when we find a new copy, append the index\n # if the queue has too many now, pop the earliest\n # if all queues with surplus have surplus[char] items, it\'s the min index among them to curr index\n\n N = len(s)\n T = N//4\n counts = Counter(s)\n queues = defaultdict(deque)\n surplus = {c: f-T for c, f in counts.items() if f > T}\n\n if not surplus: return 0\n\n for c in \'QWER\':\n if c in surplus:\n queues[c].append(-N)\n else:\n queues[c].append(N)\n\n\n best = N\n for i, c in enumerate(s):\n if c in surplus:\n q = queues[c]\n q.append(i)\n if len(q) > surplus[c]:\n q.popleft()\n\n # window currently has index i\n # we must go back to the latest (surplus[c]) copy of each surplus char to make it work\n # > +N and -N guard elements mean we don\'t have to test for empty\n best = min(best, i+1-min(q[0] for q in queues.values()))\n\n return best\n``` | 0 | Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the matrix.
**Example 2:**
**Input:** grid = \[\[3,2\],\[1,0\]\]
**Output:** 0
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 100`
* `-100 <= grid[i][j] <= 100`
**Follow up:** Could you find an `O(n + m)` solution? | Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough. |
💡💡 Neatly coded sliding window solution in python3 | replace-the-substring-for-balanced-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problme is a subproblem of 76. Minimum Window Substring - https://leetcode.com/problems/minimum-window-substring/solutions/4392528/neatly-coded-sliding-window-solution-in-python3/\nthe only difference being that here, we are also supposed to get the total unbalanced characters, form a string and pass it to the minimum window function.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn the first part we get the unbalanced count of each character - "Q", "W", "E", "R". Next, we form a string - "replace" which we are supposed to get a substring for. The rest of the approach is the same as it was for minimum window substring.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution:\n def balancedString(self, s: str) -> int:\n\n def minWindow(t):\n l = 0\n r = 0\n count = 0\n mapp = Counter(t)\n res = ""\n minn = 1e9\n while(r < len(s)):\n if s[r] in mapp:\n mapp[s[r]] -= 1\n if mapp[s[r]] >= 0:\n count += 1\n if count == len(t):\n if minn > r-l+1:\n res = s[l:r+1]\n minn = r-l+1\n while(l < r):\n if minn > r-l+1:\n res = s[l:r+1]\n minn = r-l+1\n if s[l] in mapp and mapp[s[l]] < 0:\n mapp[s[l]] += 1\n l += 1\n elif s[l] in mapp and mapp[s[l]] >= 0:\n break\n else:\n l += 1\n r += 1\n return minn\n\n qcount = wcount = ecount = rcount = 0\n n = len(s) // 4\n for i in s:\n if i == "Q":\n qcount += 1\n elif i == "W":\n wcount += 1\n elif i == "E":\n ecount += 1\n else:\n rcount += 1\n replace = ""\n if qcount > n:\n replace += "Q"*(qcount - n)\n if wcount > n:\n replace += "W"*(wcount - n)\n if ecount > n:\n replace += "E"*(ecount - n)\n if rcount > n:\n replace += "R"*(rcount - n)\n if replace == "":\n return 0\n res = minWindow(replace)\n return res\n``` | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** other string of the same length to make_ `s` _**balanced**_. If s is already **balanced**, return `0`.
**Example 1:**
**Input:** s = "QWER "
**Output:** 0
**Explanation:** s is already balanced.
**Example 2:**
**Input:** s = "QQWE "
**Output:** 1
**Explanation:** We need to replace a 'Q' to 'R', so that "RQWE " (or "QRWE ") is balanced.
**Example 3:**
**Input:** s = "QQQW "
**Output:** 2
**Explanation:** We can replace the first "QQ " to "ER ".
**Constraints:**
* `n == s.length`
* `4 <= n <= 105`
* `n` is a multiple of `4`.
* `s` contains only `'Q'`, `'W'`, `'E'`, and `'R'`. | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
💡💡 Neatly coded sliding window solution in python3 | replace-the-substring-for-balanced-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problme is a subproblem of 76. Minimum Window Substring - https://leetcode.com/problems/minimum-window-substring/solutions/4392528/neatly-coded-sliding-window-solution-in-python3/\nthe only difference being that here, we are also supposed to get the total unbalanced characters, form a string and pass it to the minimum window function.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn the first part we get the unbalanced count of each character - "Q", "W", "E", "R". Next, we form a string - "replace" which we are supposed to get a substring for. The rest of the approach is the same as it was for minimum window substring.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution:\n def balancedString(self, s: str) -> int:\n\n def minWindow(t):\n l = 0\n r = 0\n count = 0\n mapp = Counter(t)\n res = ""\n minn = 1e9\n while(r < len(s)):\n if s[r] in mapp:\n mapp[s[r]] -= 1\n if mapp[s[r]] >= 0:\n count += 1\n if count == len(t):\n if minn > r-l+1:\n res = s[l:r+1]\n minn = r-l+1\n while(l < r):\n if minn > r-l+1:\n res = s[l:r+1]\n minn = r-l+1\n if s[l] in mapp and mapp[s[l]] < 0:\n mapp[s[l]] += 1\n l += 1\n elif s[l] in mapp and mapp[s[l]] >= 0:\n break\n else:\n l += 1\n r += 1\n return minn\n\n qcount = wcount = ecount = rcount = 0\n n = len(s) // 4\n for i in s:\n if i == "Q":\n qcount += 1\n elif i == "W":\n wcount += 1\n elif i == "E":\n ecount += 1\n else:\n rcount += 1\n replace = ""\n if qcount > n:\n replace += "Q"*(qcount - n)\n if wcount > n:\n replace += "W"*(wcount - n)\n if ecount > n:\n replace += "E"*(ecount - n)\n if rcount > n:\n replace += "R"*(rcount - n)\n if replace == "":\n return 0\n res = minWindow(replace)\n return res\n``` | 0 | Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the matrix.
**Example 2:**
**Input:** grid = \[\[3,2\],\[1,0\]\]
**Output:** 0
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 100`
* `-100 <= grid[i][j] <= 100`
**Follow up:** Could you find an `O(n + m)` solution? | Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough. |
cleared code | replace-the-substring-for-balanced-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def balancedString(self, s: str) -> int:\n remaining_fre = collections.Counter(s)\n res = n = len(s)\n left = 0\n for right, c in enumerate(s):\n remaining_fre[c] -= 1\n \n while left < n and all(remaining_fre[ch] <= n/4 for ch in \'QWER\'):\n \n res = min(res, right-left+1)\n remaining_fre[s[left]] += 1 # he goes out of window! into remaining\n left += 1\n \n return res\n``` | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** other string of the same length to make_ `s` _**balanced**_. If s is already **balanced**, return `0`.
**Example 1:**
**Input:** s = "QWER "
**Output:** 0
**Explanation:** s is already balanced.
**Example 2:**
**Input:** s = "QQWE "
**Output:** 1
**Explanation:** We need to replace a 'Q' to 'R', so that "RQWE " (or "QRWE ") is balanced.
**Example 3:**
**Input:** s = "QQQW "
**Output:** 2
**Explanation:** We can replace the first "QQ " to "ER ".
**Constraints:**
* `n == s.length`
* `4 <= n <= 105`
* `n` is a multiple of `4`.
* `s` contains only `'Q'`, `'W'`, `'E'`, and `'R'`. | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
cleared code | replace-the-substring-for-balanced-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def balancedString(self, s: str) -> int:\n remaining_fre = collections.Counter(s)\n res = n = len(s)\n left = 0\n for right, c in enumerate(s):\n remaining_fre[c] -= 1\n \n while left < n and all(remaining_fre[ch] <= n/4 for ch in \'QWER\'):\n \n res = min(res, right-left+1)\n remaining_fre[s[left]] += 1 # he goes out of window! into remaining\n left += 1\n \n return res\n``` | 0 | Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the matrix.
**Example 2:**
**Input:** grid = \[\[3,2\],\[1,0\]\]
**Output:** 0
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 100`
* `-100 <= grid[i][j] <= 100`
**Follow up:** Could you find an `O(n + m)` solution? | Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough. |
sliding window[python] || O(N) Time | replace-the-substring-for-balanced-string | 0 | 1 | # Intuition\n- First thing to be noticed is every element should appear exactly n/4 times.so n will be a multiple of 4\n- But some char will appear more than n/4 supresing the other \n- now we have to find the smallest subarray which supreses other char\n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\n - take a counter to store count of elements\n- chars in sliding mean that we are repalcing this char such that every char should come n/4 times\n- after decreasing count of char in sliding window if count of all char is less than n/4 means we found a subarray\n- decrease its length to check for min\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(4)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def balancedString(self, s: str) -> int:\n count = collections.Counter(s)\n start,res = 0, len(s)\n for end in range(len(s)):\n count[s[end]] -= 1\n while start < len(s) and all( len(s)//4 >= count[j] for j in "QWER"):\n res = min(res,end-start+1)\n count[s[start]] += 1\n start += 1\n return res\n\n \n \n \n``` | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** other string of the same length to make_ `s` _**balanced**_. If s is already **balanced**, return `0`.
**Example 1:**
**Input:** s = "QWER "
**Output:** 0
**Explanation:** s is already balanced.
**Example 2:**
**Input:** s = "QQWE "
**Output:** 1
**Explanation:** We need to replace a 'Q' to 'R', so that "RQWE " (or "QRWE ") is balanced.
**Example 3:**
**Input:** s = "QQQW "
**Output:** 2
**Explanation:** We can replace the first "QQ " to "ER ".
**Constraints:**
* `n == s.length`
* `4 <= n <= 105`
* `n` is a multiple of `4`.
* `s` contains only `'Q'`, `'W'`, `'E'`, and `'R'`. | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
sliding window[python] || O(N) Time | replace-the-substring-for-balanced-string | 0 | 1 | # Intuition\n- First thing to be noticed is every element should appear exactly n/4 times.so n will be a multiple of 4\n- But some char will appear more than n/4 supresing the other \n- now we have to find the smallest subarray which supreses other char\n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\n - take a counter to store count of elements\n- chars in sliding mean that we are repalcing this char such that every char should come n/4 times\n- after decreasing count of char in sliding window if count of all char is less than n/4 means we found a subarray\n- decrease its length to check for min\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(4)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def balancedString(self, s: str) -> int:\n count = collections.Counter(s)\n start,res = 0, len(s)\n for end in range(len(s)):\n count[s[end]] -= 1\n while start < len(s) and all( len(s)//4 >= count[j] for j in "QWER"):\n res = min(res,end-start+1)\n count[s[start]] += 1\n start += 1\n return res\n\n \n \n \n``` | 0 | Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the matrix.
**Example 2:**
**Input:** grid = \[\[3,2\],\[1,0\]\]
**Output:** 0
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 100`
* `-100 <= grid[i][j] <= 100`
**Follow up:** Could you find an `O(n + m)` solution? | Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough. |
Python3 Clean Sliding Window Solution | replace-the-substring-for-balanced-string | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def balancedString(self, s: str) -> int:\n \n \n extra=""\n \n actual=len(s)//4\n count=Counter(s)\n \n for ch in count:\n if count[ch]>actual:\n extra+=(count[ch]-actual)*ch\n \n \n if not extra:\n return 0\n \n count1=Counter(extra)\n left=0\n ans=inf\n freq=Counter()\n \n for right,ch in enumerate(s):\n freq[ch]+=1\n while count1-freq==Counter():\n ans=min(ans,right-left+1)\n freq[s[left]]-=1\n left+=1\n \n return ans\n \n \n``` | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** other string of the same length to make_ `s` _**balanced**_. If s is already **balanced**, return `0`.
**Example 1:**
**Input:** s = "QWER "
**Output:** 0
**Explanation:** s is already balanced.
**Example 2:**
**Input:** s = "QQWE "
**Output:** 1
**Explanation:** We need to replace a 'Q' to 'R', so that "RQWE " (or "QRWE ") is balanced.
**Example 3:**
**Input:** s = "QQQW "
**Output:** 2
**Explanation:** We can replace the first "QQ " to "ER ".
**Constraints:**
* `n == s.length`
* `4 <= n <= 105`
* `n` is a multiple of `4`.
* `s` contains only `'Q'`, `'W'`, `'E'`, and `'R'`. | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
Python3 Clean Sliding Window Solution | replace-the-substring-for-balanced-string | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def balancedString(self, s: str) -> int:\n \n \n extra=""\n \n actual=len(s)//4\n count=Counter(s)\n \n for ch in count:\n if count[ch]>actual:\n extra+=(count[ch]-actual)*ch\n \n \n if not extra:\n return 0\n \n count1=Counter(extra)\n left=0\n ans=inf\n freq=Counter()\n \n for right,ch in enumerate(s):\n freq[ch]+=1\n while count1-freq==Counter():\n ans=min(ans,right-left+1)\n freq[s[left]]-=1\n left+=1\n \n return ans\n \n \n``` | 0 | Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the matrix.
**Example 2:**
**Input:** grid = \[\[3,2\],\[1,0\]\]
**Output:** 0
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 100`
* `-100 <= grid[i][j] <= 100`
**Follow up:** Could you find an `O(n + m)` solution? | Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough. |
Python Medium | replace-the-substring-for-balanced-string | 0 | 1 | ```\nclass Solution:\n def balancedString(self, s: str) -> int:\n M = len(s) // 4\n\n\n lookup = defaultdict(int)\n\n letters = "QWER"\n\n c = Counter(s)\n\n for l in letters:\n res = c[l] - M\n if res > 0:\n lookup[l] = res\n\n \n N = len(s)\n\n l, r = 0, 0\n\n ans = N\n\n if all (v <= 0 for v in lookup.values()):\n return 0\n\n while r < N:\n\n lookup[s[r]] -= 1\n\n\n while all(v <= 0 for v in lookup.values()):\n ans = min(ans, r - l + 1)\n\n lookup[s[l]] += 1\n l += 1\n\n r += 1\n\n return ans\n\n \n``` | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** other string of the same length to make_ `s` _**balanced**_. If s is already **balanced**, return `0`.
**Example 1:**
**Input:** s = "QWER "
**Output:** 0
**Explanation:** s is already balanced.
**Example 2:**
**Input:** s = "QQWE "
**Output:** 1
**Explanation:** We need to replace a 'Q' to 'R', so that "RQWE " (or "QRWE ") is balanced.
**Example 3:**
**Input:** s = "QQQW "
**Output:** 2
**Explanation:** We can replace the first "QQ " to "ER ".
**Constraints:**
* `n == s.length`
* `4 <= n <= 105`
* `n` is a multiple of `4`.
* `s` contains only `'Q'`, `'W'`, `'E'`, and `'R'`. | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
Python Medium | replace-the-substring-for-balanced-string | 0 | 1 | ```\nclass Solution:\n def balancedString(self, s: str) -> int:\n M = len(s) // 4\n\n\n lookup = defaultdict(int)\n\n letters = "QWER"\n\n c = Counter(s)\n\n for l in letters:\n res = c[l] - M\n if res > 0:\n lookup[l] = res\n\n \n N = len(s)\n\n l, r = 0, 0\n\n ans = N\n\n if all (v <= 0 for v in lookup.values()):\n return 0\n\n while r < N:\n\n lookup[s[r]] -= 1\n\n\n while all(v <= 0 for v in lookup.values()):\n ans = min(ans, r - l + 1)\n\n lookup[s[l]] += 1\n l += 1\n\n r += 1\n\n return ans\n\n \n``` | 0 | Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the matrix.
**Example 2:**
**Input:** grid = \[\[3,2\],\[1,0\]\]
**Output:** 0
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 100`
* `-100 <= grid[i][j] <= 100`
**Follow up:** Could you find an `O(n + m)` solution? | Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough. |
DP and Recursion in python | maximum-profit-in-job-scheduling | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\ndef fun(arr,i,memo):\n # print(i)\n if(i==len(arr)):\n return 0\n if i in memo:return memo[i]\n a=fun(arr,i+1,memo)\n bj=-1\n for j in range(i+1,len(arr)):\n if(arr[j][0]>=arr[i][1]):\n bj=j\n break\n if(bj==-1):\n b=arr[i][2]\n else:\n b=arr[i][2]+fun(arr,bj,memo)\n memo[i]=max(a,b)\n return max(a,b)\nclass Solution:\n def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:\n arr=[]\n for i in range(len(startTime)):\n arr.append([startTime[i],endTime[i],profit[i]])\n arr.sort(key=lambda x:x[0])\n # print(arr)\n return fun(arr,0,{})\n``` | 8 | We have `n` jobs, where every job is scheduled to be done from `startTime[i]` to `endTime[i]`, obtaining a profit of `profit[i]`.
You're given the `startTime`, `endTime` and `profit` arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.
If you choose a job that ends at time `X` you will be able to start another job that starts at time `X`.
**Example 1:**
**Input:** startTime = \[1,2,3,3\], endTime = \[3,4,5,6\], profit = \[50,10,40,70\]
**Output:** 120
**Explanation:** The subset chosen is the first and fourth job.
Time range \[1-3\]+\[3-6\] , we get profit of 120 = 50 + 70.
**Example 2:**
**Input:** startTime = \[1,2,3,4,6\], endTime = \[3,5,10,6,9\], profit = \[20,20,100,70,60\]
**Output:** 150
**Explanation:** The subset chosen is the first, fourth and fifth job.
Profit obtained 150 = 20 + 70 + 60.
**Example 3:**
**Input:** startTime = \[1,1,1\], endTime = \[2,3,4\], profit = \[5,6,4\]
**Output:** 6
**Constraints:**
* `1 <= startTime.length == endTime.length == profit.length <= 5 * 104`
* `1 <= startTime[i] < endTime[i] <= 109`
* `1 <= profit[i] <= 104` | null |
DP and Recursion in python | maximum-profit-in-job-scheduling | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\ndef fun(arr,i,memo):\n # print(i)\n if(i==len(arr)):\n return 0\n if i in memo:return memo[i]\n a=fun(arr,i+1,memo)\n bj=-1\n for j in range(i+1,len(arr)):\n if(arr[j][0]>=arr[i][1]):\n bj=j\n break\n if(bj==-1):\n b=arr[i][2]\n else:\n b=arr[i][2]+fun(arr,bj,memo)\n memo[i]=max(a,b)\n return max(a,b)\nclass Solution:\n def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:\n arr=[]\n for i in range(len(startTime)):\n arr.append([startTime[i],endTime[i],profit[i]])\n arr.sort(key=lambda x:x[0])\n # print(arr)\n return fun(arr,0,{})\n``` | 8 | Design an algorithm that accepts a stream of integers and retrieves the product of the last `k` integers of the stream.
Implement the `ProductOfNumbers` class:
* `ProductOfNumbers()` Initializes the object with an empty stream.
* `void add(int num)` Appends the integer `num` to the stream.
* `int getProduct(int k)` Returns the product of the last `k` numbers in the current list. You can assume that always the current list has at least `k` numbers.
The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.
**Example:**
**Input**
\[ "ProductOfNumbers ", "add ", "add ", "add ", "add ", "add ", "getProduct ", "getProduct ", "getProduct ", "add ", "getProduct "\]
\[\[\],\[3\],\[0\],\[2\],\[5\],\[4\],\[2\],\[3\],\[4\],\[8\],\[2\]\]
**Output**
\[null,null,null,null,null,null,20,40,0,null,32\]
**Explanation**
ProductOfNumbers productOfNumbers = new ProductOfNumbers();
productOfNumbers.add(3); // \[3\]
productOfNumbers.add(0); // \[3,0\]
productOfNumbers.add(2); // \[3,0,2\]
productOfNumbers.add(5); // \[3,0,2,5\]
productOfNumbers.add(4); // \[3,0,2,5,4\]
productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 \* 4 = 20
productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 \* 5 \* 4 = 40
productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 \* 2 \* 5 \* 4 = 0
productOfNumbers.add(8); // \[3,0,2,5,4,8\]
productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 \* 8 = 32
**Constraints:**
* `0 <= num <= 100`
* `1 <= k <= 4 * 104`
* At most `4 * 104` calls will be made to `add` and `getProduct`.
* The product of the stream at any point in time will fit in a **32-bit** integer. | Think on DP. Sort the elements by starting time, then define the dp[i] as the maximum profit taking elements from the suffix starting at i. Use binarySearch (lower_bound/upper_bound on C++) to get the next index for the DP transition. |
[greedy] just filtering (the easiest funny solution w/o BS, etc.) | maximum-profit-in-job-scheduling | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust filter the options instead of using binary search and other complicated things.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nChoose the best option up to the current point in time. It looks like greedy, doesn\'t it?\n# Complexity\n- Time complexity: $$O(sort)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(max(sort, n))$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n* You could find some other extraordinary solutions in my [profile](https://leetcode.com/almostmonday/) on the Solutions tab (I don\'t post obvious or not interesting solutions at all.)\n* If this was helpful, please upvote so that others can see this solution too.\n---\n\n# Code\n\n```\nclass Solution:\n def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:\n jobs = sorted(zip(startTime, endTime, profit))\n d = {0 : 0}\n for st, endNext, money in jobs:\n profitMax, dT = 0, {}\n for end, profit in d.items():\n if end <= st: profitMax = max(profitMax, profit)\n else: dT[end] = profit\n \n dT[st] = profitMax\n dT[endNext] = max(dT.get(endNext, 0), profitMax + money)\n d = dT\n \n return max(d.values())\n\n```\n\nFor larger numbers, more complex filtering could be performed:\n```\nclass Solution:\n def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:\n jobs = sorted(zip(startTime, endTime, profit))\n d = {0 : 0}\n for st, endNext, money in jobs:\n profitMax, options = 0, []\n for end, profit in d.items():\n if end <= st: profitMax = max(profitMax, profit)\n else: options.append((end, profit))\n \n options.append((st, profitMax))\n options.append((endNext, profitMax + money))\n \n options.sort(key=lambda x: (-x[1], x[0]))\n limit, d = options[0][0] + 1, {}\n for end, profit in options:\n if end < limit:\n limit = end\n d[end] = profit\n\n return options[0][1]\n``` | 1 | We have `n` jobs, where every job is scheduled to be done from `startTime[i]` to `endTime[i]`, obtaining a profit of `profit[i]`.
You're given the `startTime`, `endTime` and `profit` arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.
If you choose a job that ends at time `X` you will be able to start another job that starts at time `X`.
**Example 1:**
**Input:** startTime = \[1,2,3,3\], endTime = \[3,4,5,6\], profit = \[50,10,40,70\]
**Output:** 120
**Explanation:** The subset chosen is the first and fourth job.
Time range \[1-3\]+\[3-6\] , we get profit of 120 = 50 + 70.
**Example 2:**
**Input:** startTime = \[1,2,3,4,6\], endTime = \[3,5,10,6,9\], profit = \[20,20,100,70,60\]
**Output:** 150
**Explanation:** The subset chosen is the first, fourth and fifth job.
Profit obtained 150 = 20 + 70 + 60.
**Example 3:**
**Input:** startTime = \[1,1,1\], endTime = \[2,3,4\], profit = \[5,6,4\]
**Output:** 6
**Constraints:**
* `1 <= startTime.length == endTime.length == profit.length <= 5 * 104`
* `1 <= startTime[i] < endTime[i] <= 109`
* `1 <= profit[i] <= 104` | null |
[greedy] just filtering (the easiest funny solution w/o BS, etc.) | maximum-profit-in-job-scheduling | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust filter the options instead of using binary search and other complicated things.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nChoose the best option up to the current point in time. It looks like greedy, doesn\'t it?\n# Complexity\n- Time complexity: $$O(sort)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(max(sort, n))$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n---\n* You could find some other extraordinary solutions in my [profile](https://leetcode.com/almostmonday/) on the Solutions tab (I don\'t post obvious or not interesting solutions at all.)\n* If this was helpful, please upvote so that others can see this solution too.\n---\n\n# Code\n\n```\nclass Solution:\n def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:\n jobs = sorted(zip(startTime, endTime, profit))\n d = {0 : 0}\n for st, endNext, money in jobs:\n profitMax, dT = 0, {}\n for end, profit in d.items():\n if end <= st: profitMax = max(profitMax, profit)\n else: dT[end] = profit\n \n dT[st] = profitMax\n dT[endNext] = max(dT.get(endNext, 0), profitMax + money)\n d = dT\n \n return max(d.values())\n\n```\n\nFor larger numbers, more complex filtering could be performed:\n```\nclass Solution:\n def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:\n jobs = sorted(zip(startTime, endTime, profit))\n d = {0 : 0}\n for st, endNext, money in jobs:\n profitMax, options = 0, []\n for end, profit in d.items():\n if end <= st: profitMax = max(profitMax, profit)\n else: options.append((end, profit))\n \n options.append((st, profitMax))\n options.append((endNext, profitMax + money))\n \n options.sort(key=lambda x: (-x[1], x[0]))\n limit, d = options[0][0] + 1, {}\n for end, profit in options:\n if end < limit:\n limit = end\n d[end] = profit\n\n return options[0][1]\n``` | 1 | Design an algorithm that accepts a stream of integers and retrieves the product of the last `k` integers of the stream.
Implement the `ProductOfNumbers` class:
* `ProductOfNumbers()` Initializes the object with an empty stream.
* `void add(int num)` Appends the integer `num` to the stream.
* `int getProduct(int k)` Returns the product of the last `k` numbers in the current list. You can assume that always the current list has at least `k` numbers.
The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.
**Example:**
**Input**
\[ "ProductOfNumbers ", "add ", "add ", "add ", "add ", "add ", "getProduct ", "getProduct ", "getProduct ", "add ", "getProduct "\]
\[\[\],\[3\],\[0\],\[2\],\[5\],\[4\],\[2\],\[3\],\[4\],\[8\],\[2\]\]
**Output**
\[null,null,null,null,null,null,20,40,0,null,32\]
**Explanation**
ProductOfNumbers productOfNumbers = new ProductOfNumbers();
productOfNumbers.add(3); // \[3\]
productOfNumbers.add(0); // \[3,0\]
productOfNumbers.add(2); // \[3,0,2\]
productOfNumbers.add(5); // \[3,0,2,5\]
productOfNumbers.add(4); // \[3,0,2,5,4\]
productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 \* 4 = 20
productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 \* 5 \* 4 = 40
productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 \* 2 \* 5 \* 4 = 0
productOfNumbers.add(8); // \[3,0,2,5,4,8\]
productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 \* 8 = 32
**Constraints:**
* `0 <= num <= 100`
* `1 <= k <= 4 * 104`
* At most `4 * 104` calls will be made to `add` and `getProduct`.
* The product of the stream at any point in time will fit in a **32-bit** integer. | Think on DP. Sort the elements by starting time, then define the dp[i] as the maximum profit taking elements from the suffix starting at i. Use binarySearch (lower_bound/upper_bound on C++) to get the next index for the DP transition. |
Python 3 -> 91.68% faster. O(n) time | find-positive-integer-solution-for-a-given-equation | 0 | 1 | **Suggestions to make it better are always welcomed.**\n\nWe are working on 2 variables, x & y. Let\'s use 2 pointer approach.\n\n```\ndef findSolution(self, customfunction: \'CustomFunction\', z: int) -> List[List[int]]:\n\tx, y = 1, z\n\tpairs = []\n\t\n\twhile x<=z and y>0:\n\t\tcf = customfunction.f(x,y)\n\t\tif cf==z:\n\t\t\tpairs.append([x,y])\n\t\t\tx, y = x+1, y-1\n\t\telif cf > z:\n\t\t\ty -= 1\n\t\telse:\n\t\t\tx += 1\n\treturn pairs\n```\n\n**I hope that you\'ve found this useful.\nIn that case, please upvote. It only motivates me to write more such posts\uD83D\uDE03** | 30 | Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
* `f(x, y) < f(x + 1, y)`
* `f(x, y) < f(x, y + 1)`
The function interface is defined like this:
interface CustomFunction {
public:
// Returns some positive integer f(x, y) for two positive integers x and y based on a formula.
int f(int x, int y);
};
We will judge your solution as follows:
* The judge has a list of `9` hidden implementations of `CustomFunction`, along with a way to generate an **answer key** of all valid pairs for a specific `z`.
* The judge will receive two inputs: a `function_id` (to determine which implementation to test your code with), and the target `z`.
* The judge will call your `findSolution` and compare your results with the **answer key**.
* If your results match the **answer key**, your solution will be `Accepted`.
**Example 1:**
**Input:** function\_id = 1, z = 5
**Output:** \[\[1,4\],\[2,3\],\[3,2\],\[4,1\]\]
**Explanation:** The hidden formula for function\_id = 1 is f(x, y) = x + y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=4 -> f(1, 4) = 1 + 4 = 5.
x=2, y=3 -> f(2, 3) = 2 + 3 = 5.
x=3, y=2 -> f(3, 2) = 3 + 2 = 5.
x=4, y=1 -> f(4, 1) = 4 + 1 = 5.
**Example 2:**
**Input:** function\_id = 2, z = 5
**Output:** \[\[1,5\],\[5,1\]\]
**Explanation:** The hidden formula for function\_id = 2 is f(x, y) = x \* y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=5 -> f(1, 5) = 1 \* 5 = 5.
x=5, y=1 -> f(5, 1) = 5 \* 1 = 5.
**Constraints:**
* `1 <= function_id <= 9`
* `1 <= z <= 100`
* It is guaranteed that the solutions of `f(x, y) == z` will be in the range `1 <= x, y <= 1000`.
* It is also guaranteed that `f(x, y)` will fit in 32 bit signed integer if `1 <= x, y <= 1000`. | null |
Python 3 -> 91.68% faster. O(n) time | find-positive-integer-solution-for-a-given-equation | 0 | 1 | **Suggestions to make it better are always welcomed.**\n\nWe are working on 2 variables, x & y. Let\'s use 2 pointer approach.\n\n```\ndef findSolution(self, customfunction: \'CustomFunction\', z: int) -> List[List[int]]:\n\tx, y = 1, z\n\tpairs = []\n\t\n\twhile x<=z and y>0:\n\t\tcf = customfunction.f(x,y)\n\t\tif cf==z:\n\t\t\tpairs.append([x,y])\n\t\t\tx, y = x+1, y-1\n\t\telif cf > z:\n\t\t\ty -= 1\n\t\telse:\n\t\t\tx += 1\n\treturn pairs\n```\n\n**I hope that you\'ve found this useful.\nIn that case, please upvote. It only motivates me to write more such posts\uD83D\uDE03** | 30 | Given a string `s` consisting only of characters _a_, _b_ and _c_.
Return the number of substrings containing **at least** one occurrence of all these characters _a_, _b_ and _c_.
**Example 1:**
**Input:** s = "abcabc "
**Output:** 10
**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_abc _", "_abca _", "_abcab _", "_abcabc _", "_bca _", "_bcab _", "_bcabc _", "_cab _", "_cabc _"_ and _"_abc _"_ (**again**)_._
**Example 2:**
**Input:** s = "aaacb "
**Output:** 3
**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_aaacb _", "_aacb _"_ and _"_acb _"._
**Example 3:**
**Input:** s = "abc "
**Output:** 1
**Constraints:**
* `3 <= s.length <= 5 x 10^4`
* `s` only consists of _a_, _b_ or _c_ characters. | Loop over 1 ≤ x,y ≤ 1000 and check if f(x,y) == z. |
Two Solutions in Python 3 (beats 100%) | find-positive-integer-solution-for-a-given-equation | 0 | 1 | _Without Binary Search:_ (beats 100%)\n```\nclass Solution:\n def findSolution(self, C: \'CustomFunction\', z: int) -> List[List[int]]:\n A, Y = [], z+1 \n for x in range(1,z+1):\n if C.f(x,1) > z: return A\n for y in range(Y,0,-1):\n if C.f(x,y) == z:\n Y, _ = y-1, A.append([x,y])\n break\n return A\n\n\n```\n_With Binary Search:_ (beats 100%)\n```\nclass Solution:\n def findSolution(self, C: \'CustomFunction\', z: int) -> List[List[int]]:\n A, b = [], z+1\n for x in range(1,z+1):\n if C.f(x,1) > z: return A\n a = 1\n while C.f(x,b-1) > z:\n m = (a+b)//2\n if C.f(x,m) > z: b = m\n else: a = m\n if C.f(x,b-1) == z: b, _ = b-1, A.append([x,b-1])\n return A\n\t\t\n\t\t\n```\n_List of Functions:_\n\n1) _f(x,y) = x + y_\n2) _f(x,y) = xy_\n3) _f(x,y) = x\xB2 + y_\n4) _f(x,y) = x + y\xB2_\n5) _f(x,y) = x\xB2 + y\xB2_\n6) _f(x,y) = (x + y)\xB2_\n7) _f(x,y) = x\xB3 + y\xB3_\n8) _f(x,y) = x\xB2y_\n9) _f(x,y) = xy\xB2_\n\t\t\n\n```\n- Junaid Mansuri | 9 | Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
* `f(x, y) < f(x + 1, y)`
* `f(x, y) < f(x, y + 1)`
The function interface is defined like this:
interface CustomFunction {
public:
// Returns some positive integer f(x, y) for two positive integers x and y based on a formula.
int f(int x, int y);
};
We will judge your solution as follows:
* The judge has a list of `9` hidden implementations of `CustomFunction`, along with a way to generate an **answer key** of all valid pairs for a specific `z`.
* The judge will receive two inputs: a `function_id` (to determine which implementation to test your code with), and the target `z`.
* The judge will call your `findSolution` and compare your results with the **answer key**.
* If your results match the **answer key**, your solution will be `Accepted`.
**Example 1:**
**Input:** function\_id = 1, z = 5
**Output:** \[\[1,4\],\[2,3\],\[3,2\],\[4,1\]\]
**Explanation:** The hidden formula for function\_id = 1 is f(x, y) = x + y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=4 -> f(1, 4) = 1 + 4 = 5.
x=2, y=3 -> f(2, 3) = 2 + 3 = 5.
x=3, y=2 -> f(3, 2) = 3 + 2 = 5.
x=4, y=1 -> f(4, 1) = 4 + 1 = 5.
**Example 2:**
**Input:** function\_id = 2, z = 5
**Output:** \[\[1,5\],\[5,1\]\]
**Explanation:** The hidden formula for function\_id = 2 is f(x, y) = x \* y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=5 -> f(1, 5) = 1 \* 5 = 5.
x=5, y=1 -> f(5, 1) = 5 \* 1 = 5.
**Constraints:**
* `1 <= function_id <= 9`
* `1 <= z <= 100`
* It is guaranteed that the solutions of `f(x, y) == z` will be in the range `1 <= x, y <= 1000`.
* It is also guaranteed that `f(x, y)` will fit in 32 bit signed integer if `1 <= x, y <= 1000`. | null |
Two Solutions in Python 3 (beats 100%) | find-positive-integer-solution-for-a-given-equation | 0 | 1 | _Without Binary Search:_ (beats 100%)\n```\nclass Solution:\n def findSolution(self, C: \'CustomFunction\', z: int) -> List[List[int]]:\n A, Y = [], z+1 \n for x in range(1,z+1):\n if C.f(x,1) > z: return A\n for y in range(Y,0,-1):\n if C.f(x,y) == z:\n Y, _ = y-1, A.append([x,y])\n break\n return A\n\n\n```\n_With Binary Search:_ (beats 100%)\n```\nclass Solution:\n def findSolution(self, C: \'CustomFunction\', z: int) -> List[List[int]]:\n A, b = [], z+1\n for x in range(1,z+1):\n if C.f(x,1) > z: return A\n a = 1\n while C.f(x,b-1) > z:\n m = (a+b)//2\n if C.f(x,m) > z: b = m\n else: a = m\n if C.f(x,b-1) == z: b, _ = b-1, A.append([x,b-1])\n return A\n\t\t\n\t\t\n```\n_List of Functions:_\n\n1) _f(x,y) = x + y_\n2) _f(x,y) = xy_\n3) _f(x,y) = x\xB2 + y_\n4) _f(x,y) = x + y\xB2_\n5) _f(x,y) = x\xB2 + y\xB2_\n6) _f(x,y) = (x + y)\xB2_\n7) _f(x,y) = x\xB3 + y\xB3_\n8) _f(x,y) = x\xB2y_\n9) _f(x,y) = xy\xB2_\n\t\t\n\n```\n- Junaid Mansuri | 9 | Given a string `s` consisting only of characters _a_, _b_ and _c_.
Return the number of substrings containing **at least** one occurrence of all these characters _a_, _b_ and _c_.
**Example 1:**
**Input:** s = "abcabc "
**Output:** 10
**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_abc _", "_abca _", "_abcab _", "_abcabc _", "_bca _", "_bcab _", "_bcabc _", "_cab _", "_cabc _"_ and _"_abc _"_ (**again**)_._
**Example 2:**
**Input:** s = "aaacb "
**Output:** 3
**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_aaacb _", "_aacb _"_ and _"_acb _"._
**Example 3:**
**Input:** s = "abc "
**Output:** 1
**Constraints:**
* `3 <= s.length <= 5 x 10^4`
* `s` only consists of _a_, _b_ or _c_ characters. | Loop over 1 ≤ x,y ≤ 1000 and check if f(x,y) == z. |
Python3 | Why am I getting TLE Even though I used Binary Search to Deduce Search Space for Y? | find-positive-integer-solution-for-a-given-equation | 0 | 1 | ```\n"""\n This is the custom function interface.\n You should not implement it, or speculate about its implementation\n class CustomFunction:\n # Returns f(x, y) for any given positive integers x and y.\n # Note that f(x, y) is increasing with respect to both x and y.\n # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)\n def f(self, x, y):\n \n"""\n\nclass Solution:\n def findSolution(self, customfunction: \'CustomFunction\', z: int) -> List[List[int]]:\n ans = []\n #Basically, first find the pair solution that gives z that involves\n #lowest x(x1) and associated y(y1)!\n #From there, iterate from x1 + 1 to find solutions for other x!\n #if no solutions, move on to higher x values!\n #only look for solutions if the high value of search space\n #of candidate solutions of y for given x is greater than 1!\n \n #we can find if particular solution y exists for given x using\n #binary search on search space!\n #3 parameters: x value, l for low, h for high of boundary values\n #of current search space for y candidate solutions!\n def bin_search(x,l, h):\n nonlocal z\n #as long as we have at least one y val. to consider, continue\n #binary searching!\n while l <= h:\n middle = (l + h) // 2\n res = customfunction.f(x, middle)\n #then we found y solution!\n if(res == z):\n return middle\n #if result exceeds z, we need to look for smaller y!\n elif(res > z):\n h = middle - 1\n continue\n #otherwise, if result is below z, we need to look for higher y!\n else:\n l = middle + 1\n continue\n #if no solution, return None!\n return None\n #define the initial search space for y from 1 to 1000!\n low, high = 1, 1000\n #also, we need to keep track of current value of x we are solving for!\n #initialize it to lowest to begin with!\n cur_x = 1\n #as long as high is greater or equal to 1, continue looking\n #for more solutions!\n while high >= 1:\n #basically invoke bin_search helper!\n cand_sol = bin_search(cur_x, low, high)\n #if no solution, search sol. for higher values of x!\n if(cand_sol == None):\n cur_x += 1\n continue\n #if we found solution, then add it to answer and increment cur_x\n #and update search space for y!\n else:\n ans.append([cur_x, cand_sol])\n cur_x += 1\n #update the high boundary to be one less than cand_sol!\n high = cand_sol - 1\n return ans | 0 | Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
* `f(x, y) < f(x + 1, y)`
* `f(x, y) < f(x, y + 1)`
The function interface is defined like this:
interface CustomFunction {
public:
// Returns some positive integer f(x, y) for two positive integers x and y based on a formula.
int f(int x, int y);
};
We will judge your solution as follows:
* The judge has a list of `9` hidden implementations of `CustomFunction`, along with a way to generate an **answer key** of all valid pairs for a specific `z`.
* The judge will receive two inputs: a `function_id` (to determine which implementation to test your code with), and the target `z`.
* The judge will call your `findSolution` and compare your results with the **answer key**.
* If your results match the **answer key**, your solution will be `Accepted`.
**Example 1:**
**Input:** function\_id = 1, z = 5
**Output:** \[\[1,4\],\[2,3\],\[3,2\],\[4,1\]\]
**Explanation:** The hidden formula for function\_id = 1 is f(x, y) = x + y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=4 -> f(1, 4) = 1 + 4 = 5.
x=2, y=3 -> f(2, 3) = 2 + 3 = 5.
x=3, y=2 -> f(3, 2) = 3 + 2 = 5.
x=4, y=1 -> f(4, 1) = 4 + 1 = 5.
**Example 2:**
**Input:** function\_id = 2, z = 5
**Output:** \[\[1,5\],\[5,1\]\]
**Explanation:** The hidden formula for function\_id = 2 is f(x, y) = x \* y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=5 -> f(1, 5) = 1 \* 5 = 5.
x=5, y=1 -> f(5, 1) = 5 \* 1 = 5.
**Constraints:**
* `1 <= function_id <= 9`
* `1 <= z <= 100`
* It is guaranteed that the solutions of `f(x, y) == z` will be in the range `1 <= x, y <= 1000`.
* It is also guaranteed that `f(x, y)` will fit in 32 bit signed integer if `1 <= x, y <= 1000`. | null |
Python3 | Why am I getting TLE Even though I used Binary Search to Deduce Search Space for Y? | find-positive-integer-solution-for-a-given-equation | 0 | 1 | ```\n"""\n This is the custom function interface.\n You should not implement it, or speculate about its implementation\n class CustomFunction:\n # Returns f(x, y) for any given positive integers x and y.\n # Note that f(x, y) is increasing with respect to both x and y.\n # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)\n def f(self, x, y):\n \n"""\n\nclass Solution:\n def findSolution(self, customfunction: \'CustomFunction\', z: int) -> List[List[int]]:\n ans = []\n #Basically, first find the pair solution that gives z that involves\n #lowest x(x1) and associated y(y1)!\n #From there, iterate from x1 + 1 to find solutions for other x!\n #if no solutions, move on to higher x values!\n #only look for solutions if the high value of search space\n #of candidate solutions of y for given x is greater than 1!\n \n #we can find if particular solution y exists for given x using\n #binary search on search space!\n #3 parameters: x value, l for low, h for high of boundary values\n #of current search space for y candidate solutions!\n def bin_search(x,l, h):\n nonlocal z\n #as long as we have at least one y val. to consider, continue\n #binary searching!\n while l <= h:\n middle = (l + h) // 2\n res = customfunction.f(x, middle)\n #then we found y solution!\n if(res == z):\n return middle\n #if result exceeds z, we need to look for smaller y!\n elif(res > z):\n h = middle - 1\n continue\n #otherwise, if result is below z, we need to look for higher y!\n else:\n l = middle + 1\n continue\n #if no solution, return None!\n return None\n #define the initial search space for y from 1 to 1000!\n low, high = 1, 1000\n #also, we need to keep track of current value of x we are solving for!\n #initialize it to lowest to begin with!\n cur_x = 1\n #as long as high is greater or equal to 1, continue looking\n #for more solutions!\n while high >= 1:\n #basically invoke bin_search helper!\n cand_sol = bin_search(cur_x, low, high)\n #if no solution, search sol. for higher values of x!\n if(cand_sol == None):\n cur_x += 1\n continue\n #if we found solution, then add it to answer and increment cur_x\n #and update search space for y!\n else:\n ans.append([cur_x, cand_sol])\n cur_x += 1\n #update the high boundary to be one less than cand_sol!\n high = cand_sol - 1\n return ans | 0 | Given a string `s` consisting only of characters _a_, _b_ and _c_.
Return the number of substrings containing **at least** one occurrence of all these characters _a_, _b_ and _c_.
**Example 1:**
**Input:** s = "abcabc "
**Output:** 10
**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_abc _", "_abca _", "_abcab _", "_abcabc _", "_bca _", "_bcab _", "_bcabc _", "_cab _", "_cabc _"_ and _"_abc _"_ (**again**)_._
**Example 2:**
**Input:** s = "aaacb "
**Output:** 3
**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_aaacb _", "_aacb _"_ and _"_acb _"._
**Example 3:**
**Input:** s = "abc "
**Output:** 1
**Constraints:**
* `3 <= s.length <= 5 x 10^4`
* `s` only consists of _a_, _b_ or _c_ characters. | Loop over 1 ≤ x,y ≤ 1000 and check if f(x,y) == z. |
[Python3] Good enough | find-positive-integer-solution-for-a-given-equation | 0 | 1 | ``` Python3 []\n"""\n This is the custom function interface.\n You should not implement it, or speculate about its implementation\n class CustomFunction:\n # Returns f(x, y) for any given positive integers x and y.\n # Note that f(x, y) is increasing with respect to both x and y.\n # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)\n def f(self, x, y):\n \n"""\n\nclass Solution:\n def findSolution(self, customfunction: \'CustomFunction\', z: int) -> List[List[int]]:\n solutions = []\n\n for x in range(1, 1001):\n for y in range(1, 1001):\n if customfunction.f(x,y)>z:\n break\n elif customfunction.f(x,y)==z:\n solutions.append([x,y])\n \n if customfunction.f(x,1)>z:\n break\n \n return solutions\n``` | 0 | Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
* `f(x, y) < f(x + 1, y)`
* `f(x, y) < f(x, y + 1)`
The function interface is defined like this:
interface CustomFunction {
public:
// Returns some positive integer f(x, y) for two positive integers x and y based on a formula.
int f(int x, int y);
};
We will judge your solution as follows:
* The judge has a list of `9` hidden implementations of `CustomFunction`, along with a way to generate an **answer key** of all valid pairs for a specific `z`.
* The judge will receive two inputs: a `function_id` (to determine which implementation to test your code with), and the target `z`.
* The judge will call your `findSolution` and compare your results with the **answer key**.
* If your results match the **answer key**, your solution will be `Accepted`.
**Example 1:**
**Input:** function\_id = 1, z = 5
**Output:** \[\[1,4\],\[2,3\],\[3,2\],\[4,1\]\]
**Explanation:** The hidden formula for function\_id = 1 is f(x, y) = x + y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=4 -> f(1, 4) = 1 + 4 = 5.
x=2, y=3 -> f(2, 3) = 2 + 3 = 5.
x=3, y=2 -> f(3, 2) = 3 + 2 = 5.
x=4, y=1 -> f(4, 1) = 4 + 1 = 5.
**Example 2:**
**Input:** function\_id = 2, z = 5
**Output:** \[\[1,5\],\[5,1\]\]
**Explanation:** The hidden formula for function\_id = 2 is f(x, y) = x \* y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=5 -> f(1, 5) = 1 \* 5 = 5.
x=5, y=1 -> f(5, 1) = 5 \* 1 = 5.
**Constraints:**
* `1 <= function_id <= 9`
* `1 <= z <= 100`
* It is guaranteed that the solutions of `f(x, y) == z` will be in the range `1 <= x, y <= 1000`.
* It is also guaranteed that `f(x, y)` will fit in 32 bit signed integer if `1 <= x, y <= 1000`. | null |
[Python3] Good enough | find-positive-integer-solution-for-a-given-equation | 0 | 1 | ``` Python3 []\n"""\n This is the custom function interface.\n You should not implement it, or speculate about its implementation\n class CustomFunction:\n # Returns f(x, y) for any given positive integers x and y.\n # Note that f(x, y) is increasing with respect to both x and y.\n # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)\n def f(self, x, y):\n \n"""\n\nclass Solution:\n def findSolution(self, customfunction: \'CustomFunction\', z: int) -> List[List[int]]:\n solutions = []\n\n for x in range(1, 1001):\n for y in range(1, 1001):\n if customfunction.f(x,y)>z:\n break\n elif customfunction.f(x,y)==z:\n solutions.append([x,y])\n \n if customfunction.f(x,1)>z:\n break\n \n return solutions\n``` | 0 | Given a string `s` consisting only of characters _a_, _b_ and _c_.
Return the number of substrings containing **at least** one occurrence of all these characters _a_, _b_ and _c_.
**Example 1:**
**Input:** s = "abcabc "
**Output:** 10
**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_abc _", "_abca _", "_abcab _", "_abcabc _", "_bca _", "_bcab _", "_bcabc _", "_cab _", "_cabc _"_ and _"_abc _"_ (**again**)_._
**Example 2:**
**Input:** s = "aaacb "
**Output:** 3
**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_aaacb _", "_aacb _"_ and _"_acb _"._
**Example 3:**
**Input:** s = "abc "
**Output:** 1
**Constraints:**
* `3 <= s.length <= 5 x 10^4`
* `s` only consists of _a_, _b_ or _c_ characters. | Loop over 1 ≤ x,y ≤ 1000 and check if f(x,y) == z. |
Smart brute force || Faster than 80% | find-positive-integer-solution-for-a-given-equation | 0 | 1 | # Intuition\nSimply do a linear serach and as we know the function is monotonically increasing if f(x, 1) is greater than z then any value after that would bre greater hence we can simply break\nalso if f(x, y) is greater than > z then f(x, y+1) will be definitely greater hence we can break out of the inner loop\n\n# Code\n```\n"""\n This is the custom function interface.\n You should not implement it, or speculate about its implementation\n class CustomFunction:\n # Returns f(x, y) for any given positive integers x and y.\n # Note that f(x, y) is increasing with respect to both x and y.\n # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)\n def f(self, x, y):\n \n"""\n\nclass Solution:\n def findSolution(self, customfunction: \'CustomFunction\', z: int) -> List[List[int]]:\n ans = []\n\n for i in range(1, 1001):\n if customfunction.f(i, 1) > z:\n break\n for j in range(1, 1001):\n if customfunction.f(i, j) == z:\n ans.append([i, j])\n if customfunction.f(i, j) > z:\n break\n \n return ans\n``` | 0 | Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
* `f(x, y) < f(x + 1, y)`
* `f(x, y) < f(x, y + 1)`
The function interface is defined like this:
interface CustomFunction {
public:
// Returns some positive integer f(x, y) for two positive integers x and y based on a formula.
int f(int x, int y);
};
We will judge your solution as follows:
* The judge has a list of `9` hidden implementations of `CustomFunction`, along with a way to generate an **answer key** of all valid pairs for a specific `z`.
* The judge will receive two inputs: a `function_id` (to determine which implementation to test your code with), and the target `z`.
* The judge will call your `findSolution` and compare your results with the **answer key**.
* If your results match the **answer key**, your solution will be `Accepted`.
**Example 1:**
**Input:** function\_id = 1, z = 5
**Output:** \[\[1,4\],\[2,3\],\[3,2\],\[4,1\]\]
**Explanation:** The hidden formula for function\_id = 1 is f(x, y) = x + y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=4 -> f(1, 4) = 1 + 4 = 5.
x=2, y=3 -> f(2, 3) = 2 + 3 = 5.
x=3, y=2 -> f(3, 2) = 3 + 2 = 5.
x=4, y=1 -> f(4, 1) = 4 + 1 = 5.
**Example 2:**
**Input:** function\_id = 2, z = 5
**Output:** \[\[1,5\],\[5,1\]\]
**Explanation:** The hidden formula for function\_id = 2 is f(x, y) = x \* y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=5 -> f(1, 5) = 1 \* 5 = 5.
x=5, y=1 -> f(5, 1) = 5 \* 1 = 5.
**Constraints:**
* `1 <= function_id <= 9`
* `1 <= z <= 100`
* It is guaranteed that the solutions of `f(x, y) == z` will be in the range `1 <= x, y <= 1000`.
* It is also guaranteed that `f(x, y)` will fit in 32 bit signed integer if `1 <= x, y <= 1000`. | null |
Smart brute force || Faster than 80% | find-positive-integer-solution-for-a-given-equation | 0 | 1 | # Intuition\nSimply do a linear serach and as we know the function is monotonically increasing if f(x, 1) is greater than z then any value after that would bre greater hence we can simply break\nalso if f(x, y) is greater than > z then f(x, y+1) will be definitely greater hence we can break out of the inner loop\n\n# Code\n```\n"""\n This is the custom function interface.\n You should not implement it, or speculate about its implementation\n class CustomFunction:\n # Returns f(x, y) for any given positive integers x and y.\n # Note that f(x, y) is increasing with respect to both x and y.\n # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)\n def f(self, x, y):\n \n"""\n\nclass Solution:\n def findSolution(self, customfunction: \'CustomFunction\', z: int) -> List[List[int]]:\n ans = []\n\n for i in range(1, 1001):\n if customfunction.f(i, 1) > z:\n break\n for j in range(1, 1001):\n if customfunction.f(i, j) == z:\n ans.append([i, j])\n if customfunction.f(i, j) > z:\n break\n \n return ans\n``` | 0 | Given a string `s` consisting only of characters _a_, _b_ and _c_.
Return the number of substrings containing **at least** one occurrence of all these characters _a_, _b_ and _c_.
**Example 1:**
**Input:** s = "abcabc "
**Output:** 10
**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_abc _", "_abca _", "_abcab _", "_abcabc _", "_bca _", "_bcab _", "_bcabc _", "_cab _", "_cabc _"_ and _"_abc _"_ (**again**)_._
**Example 2:**
**Input:** s = "aaacb "
**Output:** 3
**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_aaacb _", "_aacb _"_ and _"_acb _"._
**Example 3:**
**Input:** s = "abc "
**Output:** 1
**Constraints:**
* `3 <= s.length <= 5 x 10^4`
* `s` only consists of _a_, _b_ or _c_ characters. | Loop over 1 ≤ x,y ≤ 1000 and check if f(x,y) == z. |
Find positive integer solution for a given equation | find-positive-integer-solution-for-a-given-equation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\n"""\n This is the custom function interface.\n You should not implement it, or speculate about its implementation\n class CustomFunction:\n # Returns f(x, y) for any given positive integers x and y.\n # Note that f(x, y) is increasing with respect to both x and y.\n # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)\n def f(self, x, y):\n \n"""\n\nclass Solution:\n def findSolution(self, customfunction: \'CustomFunction\', z: int) -> List[List[int]]:\n y=1000\n ans=[]\n for x in range(1,1001):\n while y>1 and customfunction.f(x,y)>z:\n y-=1\n if customfunction.f(x,y)==z:\n ans.append([x,y])\n return ans\n``` | 0 | Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
* `f(x, y) < f(x + 1, y)`
* `f(x, y) < f(x, y + 1)`
The function interface is defined like this:
interface CustomFunction {
public:
// Returns some positive integer f(x, y) for two positive integers x and y based on a formula.
int f(int x, int y);
};
We will judge your solution as follows:
* The judge has a list of `9` hidden implementations of `CustomFunction`, along with a way to generate an **answer key** of all valid pairs for a specific `z`.
* The judge will receive two inputs: a `function_id` (to determine which implementation to test your code with), and the target `z`.
* The judge will call your `findSolution` and compare your results with the **answer key**.
* If your results match the **answer key**, your solution will be `Accepted`.
**Example 1:**
**Input:** function\_id = 1, z = 5
**Output:** \[\[1,4\],\[2,3\],\[3,2\],\[4,1\]\]
**Explanation:** The hidden formula for function\_id = 1 is f(x, y) = x + y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=4 -> f(1, 4) = 1 + 4 = 5.
x=2, y=3 -> f(2, 3) = 2 + 3 = 5.
x=3, y=2 -> f(3, 2) = 3 + 2 = 5.
x=4, y=1 -> f(4, 1) = 4 + 1 = 5.
**Example 2:**
**Input:** function\_id = 2, z = 5
**Output:** \[\[1,5\],\[5,1\]\]
**Explanation:** The hidden formula for function\_id = 2 is f(x, y) = x \* y.
The following positive integer values of x and y make f(x, y) equal to 5:
x=1, y=5 -> f(1, 5) = 1 \* 5 = 5.
x=5, y=1 -> f(5, 1) = 5 \* 1 = 5.
**Constraints:**
* `1 <= function_id <= 9`
* `1 <= z <= 100`
* It is guaranteed that the solutions of `f(x, y) == z` will be in the range `1 <= x, y <= 1000`.
* It is also guaranteed that `f(x, y)` will fit in 32 bit signed integer if `1 <= x, y <= 1000`. | null |
Find positive integer solution for a given equation | find-positive-integer-solution-for-a-given-equation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\n"""\n This is the custom function interface.\n You should not implement it, or speculate about its implementation\n class CustomFunction:\n # Returns f(x, y) for any given positive integers x and y.\n # Note that f(x, y) is increasing with respect to both x and y.\n # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)\n def f(self, x, y):\n \n"""\n\nclass Solution:\n def findSolution(self, customfunction: \'CustomFunction\', z: int) -> List[List[int]]:\n y=1000\n ans=[]\n for x in range(1,1001):\n while y>1 and customfunction.f(x,y)>z:\n y-=1\n if customfunction.f(x,y)==z:\n ans.append([x,y])\n return ans\n``` | 0 | Given a string `s` consisting only of characters _a_, _b_ and _c_.
Return the number of substrings containing **at least** one occurrence of all these characters _a_, _b_ and _c_.
**Example 1:**
**Input:** s = "abcabc "
**Output:** 10
**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_abc _", "_abca _", "_abcab _", "_abcabc _", "_bca _", "_bcab _", "_bcabc _", "_cab _", "_cabc _"_ and _"_abc _"_ (**again**)_._
**Example 2:**
**Input:** s = "aaacb "
**Output:** 3
**Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_aaacb _", "_aacb _"_ and _"_acb _"._
**Example 3:**
**Input:** s = "abc "
**Output:** 1
**Constraints:**
* `3 <= s.length <= 5 x 10^4`
* `s` only consists of _a_, _b_ or _c_ characters. | Loop over 1 ≤ x,y ≤ 1000 and check if f(x,y) == z. |
Python 3: A Bit of Clever Pattern Recognition | circular-permutation-in-binary-representation | 0 | 1 | # Intuition\r\n\r\nThis is a kind of tricky problem to work out if you try to start with dynamic programming.\r\n\r\nSo instead I tackled it by finding a pattern. First we note that if we can find a pattern starting with 0, then we can do a circular shift of the array to get the final answer.\r\n* `n=1: [0, 1]`\r\n* `n=2: [00, 01, 11, 10]`\r\n* `n=3: [000, 001, 011, 010, 110, 111, 101, 100]`\r\n\r\nA pattern begins to emerge, where for `n=3` I realized I was reading the solution for `n=2` to build the solution from `n=3`. Let\'s look at the last 2 bits for `n=3`:\r\n\r\nASCII art:\r\n```a\r\nn=3: 000, 001, 011, 010, 110, 111, 101, 100\r\n 00 01 11 10 10 11 01 00\r\n ----------------- -----------------\r\n n=2 solution reverse of n=2\r\n with 0 in front solution with\r\n i.e. just the a 1 in front\r\n n=2 solution \r\n```\r\n\r\nThe pattern makes some sense:\r\n* if we have the answer `S[n]` for the `n-bit` sequence\r\n* then we know that `S[n]` has the right property: it varies by only 1 bit difference each pair, and the first and last are one bit off\r\n* if we do `S[n] + reverse(S[n])` then we *almost* have a solution, with two problems:\r\n * the middle two elements are the same\r\n * the first and last elements are the same\r\n * because we took `S[n]` and appended the reverse\r\n* we can fix both problems to adding `100_2` to the reversed list.\r\n * then the middle two elements are one off\r\n * the first and last two elements are one off\r\n * and we traversed all possible values\r\n\r\nFinal recurrence relation: `S[n] = S[n-1] + [p + k for k in reversed(S[n-1])]`\r\n * `S[n]` is the answer for `n` bits\r\n * `p` is `1 << (n-1)`\r\n\r\nSo we take the answer for `n-1`, and append the reverse of it with `1 << (n-1)` added to each element.\r\n\r\n# Approach\r\n\r\nNot much to add. I store the current sequence length as `S`, starting with `n=1`.\r\n\r\nThen I use `list.extend` to apply its reverse, with `p` added, to form the sequence for the next list.\r\n\r\nThis produces `[0, ...]`. So I just find the index of `start` using `list.index(start)` and do the circular rotation of the array.\r\n\r\nThat rotation works because we know the first and last are 1 bit off, and all pairs are 1 bit off, so any circular rotation of the array has the expected property too.\r\n\r\n# Complexity\r\n- Time complexity: `O(2^n)`\r\n\r\n- Space complexity: `O(2^n)` for the final rotation\r\n\r\nThe space complexity can be reduced to just O(1) extra space if we did a smarter rotation. You can rotate the array in place with a temp variable.\r\n\r\nBut rotating with the temp variable is annoying and prone to off-by-one errors so I didn\'t bother.\r\n\r\n\r\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\r\n\r\n# Code\r\n```\r\nclass Solution:\r\n def circularPermutation(self, n: int, start: int) -> List[int]:\r\n # super brute force: DFS + backtracking\r\n # smarter: pattern\r\n\r\n # wlog we can make the permutation of 0..2^n-1 starting with zero, then cycle through to start at `start`\r\n\r\n # n = 1: 0, 1\r\n # n = 2: 00, 01, 11, 10\r\n # so take 0S_{n-1} and 1rev(S_{n-1}) (?)\r\n # because we know S_{n-1} has the right property, and same with rev(S_{n-1})\r\n # so S + rev(S) has that property, EXCEPT\r\n # the outer two: same element\r\n # and the inner two: same element\r\n # so if we put a 1 in front of rev(S) then we\'re good\r\n\r\n if n == 1:\r\n if start == 0: return [0, 1]\r\n else: return [1, 0]\r\n\r\n S = [0, 1]\r\n for m in range(2, n+1):\r\n # existing S is S_{n-1}; we leave it as-is ("prepend 0")\r\n # then we append elements in reverse with a 1 in front, for m=2 we want to add 10 == 1 << (m-1)\r\n p = 1 << (m-1)\r\n S.extend(p + S[k] for k in range(len(S)-1, -1, -1))\r\n\r\n i = S.index(start)\r\n if i: return S[i:] + S[:i]\r\n else: return S\r\n``` | 0 | Given 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that :
* `p[0] = start`
* `p[i]` and `p[i+1]` differ by only one bit in their binary representation.
* `p[0]` and `p[2^n -1]` must also differ by only one bit in their binary representation.
**Example 1:**
**Input:** n = 2, start = 3
**Output:** \[3,2,0,1\]
**Explanation:** The binary representation of the permutation is (11,10,00,01).
All the adjacent element differ by one bit. Another valid permutation is \[3,1,0,2\]
**Example 2:**
**Input:** n = 3, start = 2
**Output:** \[2,6,7,5,4,0,1,3\]
**Explanation:** The binary representation of the permutation is (010,110,111,101,100,000,001,011).
**Constraints:**
* `1 <= n <= 16`
* `0 <= start < 2 ^ n` | Create a hashmap from letter to position on the board. Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board. |
Python 3: A Bit of Clever Pattern Recognition | circular-permutation-in-binary-representation | 0 | 1 | # Intuition\r\n\r\nThis is a kind of tricky problem to work out if you try to start with dynamic programming.\r\n\r\nSo instead I tackled it by finding a pattern. First we note that if we can find a pattern starting with 0, then we can do a circular shift of the array to get the final answer.\r\n* `n=1: [0, 1]`\r\n* `n=2: [00, 01, 11, 10]`\r\n* `n=3: [000, 001, 011, 010, 110, 111, 101, 100]`\r\n\r\nA pattern begins to emerge, where for `n=3` I realized I was reading the solution for `n=2` to build the solution from `n=3`. Let\'s look at the last 2 bits for `n=3`:\r\n\r\nASCII art:\r\n```a\r\nn=3: 000, 001, 011, 010, 110, 111, 101, 100\r\n 00 01 11 10 10 11 01 00\r\n ----------------- -----------------\r\n n=2 solution reverse of n=2\r\n with 0 in front solution with\r\n i.e. just the a 1 in front\r\n n=2 solution \r\n```\r\n\r\nThe pattern makes some sense:\r\n* if we have the answer `S[n]` for the `n-bit` sequence\r\n* then we know that `S[n]` has the right property: it varies by only 1 bit difference each pair, and the first and last are one bit off\r\n* if we do `S[n] + reverse(S[n])` then we *almost* have a solution, with two problems:\r\n * the middle two elements are the same\r\n * the first and last elements are the same\r\n * because we took `S[n]` and appended the reverse\r\n* we can fix both problems to adding `100_2` to the reversed list.\r\n * then the middle two elements are one off\r\n * the first and last two elements are one off\r\n * and we traversed all possible values\r\n\r\nFinal recurrence relation: `S[n] = S[n-1] + [p + k for k in reversed(S[n-1])]`\r\n * `S[n]` is the answer for `n` bits\r\n * `p` is `1 << (n-1)`\r\n\r\nSo we take the answer for `n-1`, and append the reverse of it with `1 << (n-1)` added to each element.\r\n\r\n# Approach\r\n\r\nNot much to add. I store the current sequence length as `S`, starting with `n=1`.\r\n\r\nThen I use `list.extend` to apply its reverse, with `p` added, to form the sequence for the next list.\r\n\r\nThis produces `[0, ...]`. So I just find the index of `start` using `list.index(start)` and do the circular rotation of the array.\r\n\r\nThat rotation works because we know the first and last are 1 bit off, and all pairs are 1 bit off, so any circular rotation of the array has the expected property too.\r\n\r\n# Complexity\r\n- Time complexity: `O(2^n)`\r\n\r\n- Space complexity: `O(2^n)` for the final rotation\r\n\r\nThe space complexity can be reduced to just O(1) extra space if we did a smarter rotation. You can rotate the array in place with a temp variable.\r\n\r\nBut rotating with the temp variable is annoying and prone to off-by-one errors so I didn\'t bother.\r\n\r\n\r\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\r\n\r\n# Code\r\n```\r\nclass Solution:\r\n def circularPermutation(self, n: int, start: int) -> List[int]:\r\n # super brute force: DFS + backtracking\r\n # smarter: pattern\r\n\r\n # wlog we can make the permutation of 0..2^n-1 starting with zero, then cycle through to start at `start`\r\n\r\n # n = 1: 0, 1\r\n # n = 2: 00, 01, 11, 10\r\n # so take 0S_{n-1} and 1rev(S_{n-1}) (?)\r\n # because we know S_{n-1} has the right property, and same with rev(S_{n-1})\r\n # so S + rev(S) has that property, EXCEPT\r\n # the outer two: same element\r\n # and the inner two: same element\r\n # so if we put a 1 in front of rev(S) then we\'re good\r\n\r\n if n == 1:\r\n if start == 0: return [0, 1]\r\n else: return [1, 0]\r\n\r\n S = [0, 1]\r\n for m in range(2, n+1):\r\n # existing S is S_{n-1}; we leave it as-is ("prepend 0")\r\n # then we append elements in reverse with a 1 in front, for m=2 we want to add 10 == 1 << (m-1)\r\n p = 1 << (m-1)\r\n S.extend(p + S[k] for k in range(len(S)-1, -1, -1))\r\n\r\n i = S.index(start)\r\n if i: return S[i:] + S[:i]\r\n else: return S\r\n``` | 0 | Given `n` orders, each order consist in pickup and delivery services.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
Since the answer may be too large, return it modulo 10^9 + 7.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation:** Unique order (P1, D1), Delivery 1 always is after of Pickup 1.
**Example 2:**
**Input:** n = 2
**Output:** 6
**Explanation:** All possible orders:
(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).
This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.
**Example 3:**
**Input:** n = 3
**Output:** 90
**Constraints:**
* `1 <= n <= 500`
Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that : p\[0\] = start, p\[i\] and p\[i+1\] differ by only one bit for all 0 <= i < 2^n - 1. | Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start. |
Python | circular-permutation-in-binary-representation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def circularPermutation(self, n: int, start: int) -> List[int]:\n res=[]\n for i in range(pow(2,n)):\n res.append(i^(i>>1))\n ind=res.index(start)\n res=res[ind:]+res[:ind]\n return res\n``` | 0 | Given 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that :
* `p[0] = start`
* `p[i]` and `p[i+1]` differ by only one bit in their binary representation.
* `p[0]` and `p[2^n -1]` must also differ by only one bit in their binary representation.
**Example 1:**
**Input:** n = 2, start = 3
**Output:** \[3,2,0,1\]
**Explanation:** The binary representation of the permutation is (11,10,00,01).
All the adjacent element differ by one bit. Another valid permutation is \[3,1,0,2\]
**Example 2:**
**Input:** n = 3, start = 2
**Output:** \[2,6,7,5,4,0,1,3\]
**Explanation:** The binary representation of the permutation is (010,110,111,101,100,000,001,011).
**Constraints:**
* `1 <= n <= 16`
* `0 <= start < 2 ^ n` | Create a hashmap from letter to position on the board. Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board. |
Python | circular-permutation-in-binary-representation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def circularPermutation(self, n: int, start: int) -> List[int]:\n res=[]\n for i in range(pow(2,n)):\n res.append(i^(i>>1))\n ind=res.index(start)\n res=res[ind:]+res[:ind]\n return res\n``` | 0 | Given `n` orders, each order consist in pickup and delivery services.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
Since the answer may be too large, return it modulo 10^9 + 7.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation:** Unique order (P1, D1), Delivery 1 always is after of Pickup 1.
**Example 2:**
**Input:** n = 2
**Output:** 6
**Explanation:** All possible orders:
(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).
This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.
**Example 3:**
**Input:** n = 3
**Output:** 90
**Constraints:**
* `1 <= n <= 500`
Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that : p\[0\] = start, p\[i\] and p\[i+1\] differ by only one bit for all 0 <= i < 2^n - 1. | Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start. |
Python (Simple Gray's code) | circular-permutation-in-binary-representation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def circularPermutation(self, n, start):\n res = [i^(i//2) for i in range(1<<n)]\n idx = res.index(start)\n return res[idx:] + res[:idx]\n\n \n \n \n \n``` | 0 | Given 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that :
* `p[0] = start`
* `p[i]` and `p[i+1]` differ by only one bit in their binary representation.
* `p[0]` and `p[2^n -1]` must also differ by only one bit in their binary representation.
**Example 1:**
**Input:** n = 2, start = 3
**Output:** \[3,2,0,1\]
**Explanation:** The binary representation of the permutation is (11,10,00,01).
All the adjacent element differ by one bit. Another valid permutation is \[3,1,0,2\]
**Example 2:**
**Input:** n = 3, start = 2
**Output:** \[2,6,7,5,4,0,1,3\]
**Explanation:** The binary representation of the permutation is (010,110,111,101,100,000,001,011).
**Constraints:**
* `1 <= n <= 16`
* `0 <= start < 2 ^ n` | Create a hashmap from letter to position on the board. Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board. |
Python (Simple Gray's code) | circular-permutation-in-binary-representation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def circularPermutation(self, n, start):\n res = [i^(i//2) for i in range(1<<n)]\n idx = res.index(start)\n return res[idx:] + res[:idx]\n\n \n \n \n \n``` | 0 | Given `n` orders, each order consist in pickup and delivery services.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
Since the answer may be too large, return it modulo 10^9 + 7.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation:** Unique order (P1, D1), Delivery 1 always is after of Pickup 1.
**Example 2:**
**Input:** n = 2
**Output:** 6
**Explanation:** All possible orders:
(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).
This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.
**Example 3:**
**Input:** n = 3
**Output:** 90
**Constraints:**
* `1 <= n <= 500`
Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that : p\[0\] = start, p\[i\] and p\[i+1\] differ by only one bit for all 0 <= i < 2^n - 1. | Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start. |
[Python] Simple DFS approach | circular-permutation-in-binary-representation | 0 | 1 | # Code\n```\nclass Solution:\n def circularPermutation(self, n: int, start: int) -> List[int]:\n N = 1<<n\n vis = [False]*N\n def dfs(u,st):\n vis[u] = True\n st.append(u)\n for i in range(n):\n v = u^(1<<i)\n if(not vis[v]): dfs(v,st)\n res = []\n dfs(start,res)\n return res\n``` | 0 | Given 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that :
* `p[0] = start`
* `p[i]` and `p[i+1]` differ by only one bit in their binary representation.
* `p[0]` and `p[2^n -1]` must also differ by only one bit in their binary representation.
**Example 1:**
**Input:** n = 2, start = 3
**Output:** \[3,2,0,1\]
**Explanation:** The binary representation of the permutation is (11,10,00,01).
All the adjacent element differ by one bit. Another valid permutation is \[3,1,0,2\]
**Example 2:**
**Input:** n = 3, start = 2
**Output:** \[2,6,7,5,4,0,1,3\]
**Explanation:** The binary representation of the permutation is (010,110,111,101,100,000,001,011).
**Constraints:**
* `1 <= n <= 16`
* `0 <= start < 2 ^ n` | Create a hashmap from letter to position on the board. Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board. |
[Python] Simple DFS approach | circular-permutation-in-binary-representation | 0 | 1 | # Code\n```\nclass Solution:\n def circularPermutation(self, n: int, start: int) -> List[int]:\n N = 1<<n\n vis = [False]*N\n def dfs(u,st):\n vis[u] = True\n st.append(u)\n for i in range(n):\n v = u^(1<<i)\n if(not vis[v]): dfs(v,st)\n res = []\n dfs(start,res)\n return res\n``` | 0 | Given `n` orders, each order consist in pickup and delivery services.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
Since the answer may be too large, return it modulo 10^9 + 7.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation:** Unique order (P1, D1), Delivery 1 always is after of Pickup 1.
**Example 2:**
**Input:** n = 2
**Output:** 6
**Explanation:** All possible orders:
(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).
This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.
**Example 3:**
**Input:** n = 3
**Output:** 90
**Constraints:**
* `1 <= n <= 500`
Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that : p\[0\] = start, p\[i\] and p\[i+1\] differ by only one bit for all 0 <= i < 2^n - 1. | Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start. |
Python solution beats 98%. W/ explanation | circular-permutation-in-binary-representation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is to find all the possible binary permutations of a given length n, and starting from a given starting number. The circular permutation means that the permutations will be arranged in a circular manner, so that the last element of the list is connected to the first element.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach is to generate all the possible binary permutations of length n, starting from the given starting number. The solution uses a Gray code sequence generation algorithm, which generates a sequence of binary numbers such that each number in the sequence differs by only one bit from the previous number. This property of Gray code sequences allows for a simple and efficient solution to the problem.\n\n\n# Complexity\n- Time complexity: $$O(2^n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(2^n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def circularPermutation(self, n: int, start: int) -> List[int]:\n res = [start]\n for i in range(n):\n res += [x ^ (1 << i) for x in res[::-1]]\n return res\n``` | 0 | Given 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that :
* `p[0] = start`
* `p[i]` and `p[i+1]` differ by only one bit in their binary representation.
* `p[0]` and `p[2^n -1]` must also differ by only one bit in their binary representation.
**Example 1:**
**Input:** n = 2, start = 3
**Output:** \[3,2,0,1\]
**Explanation:** The binary representation of the permutation is (11,10,00,01).
All the adjacent element differ by one bit. Another valid permutation is \[3,1,0,2\]
**Example 2:**
**Input:** n = 3, start = 2
**Output:** \[2,6,7,5,4,0,1,3\]
**Explanation:** The binary representation of the permutation is (010,110,111,101,100,000,001,011).
**Constraints:**
* `1 <= n <= 16`
* `0 <= start < 2 ^ n` | Create a hashmap from letter to position on the board. Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board. |
Python solution beats 98%. W/ explanation | circular-permutation-in-binary-representation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is to find all the possible binary permutations of a given length n, and starting from a given starting number. The circular permutation means that the permutations will be arranged in a circular manner, so that the last element of the list is connected to the first element.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach is to generate all the possible binary permutations of length n, starting from the given starting number. The solution uses a Gray code sequence generation algorithm, which generates a sequence of binary numbers such that each number in the sequence differs by only one bit from the previous number. This property of Gray code sequences allows for a simple and efficient solution to the problem.\n\n\n# Complexity\n- Time complexity: $$O(2^n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(2^n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def circularPermutation(self, n: int, start: int) -> List[int]:\n res = [start]\n for i in range(n):\n res += [x ^ (1 << i) for x in res[::-1]]\n return res\n``` | 0 | Given `n` orders, each order consist in pickup and delivery services.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
Since the answer may be too large, return it modulo 10^9 + 7.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation:** Unique order (P1, D1), Delivery 1 always is after of Pickup 1.
**Example 2:**
**Input:** n = 2
**Output:** 6
**Explanation:** All possible orders:
(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).
This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.
**Example 3:**
**Input:** n = 3
**Output:** 90
**Constraints:**
* `1 <= n <= 500`
Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that : p\[0\] = start, p\[i\] and p\[i+1\] differ by only one bit for all 0 <= i < 2^n - 1. | Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start. |
Python Elegant & Short | DP | maximum-length-of-a-concatenated-string-with-unique-characters | 0 | 1 | ```\nclass Solution:\n """\n Time: O(n^2)\n Memory: O(n^2)\n """\n\n def maxLength(self, sequences: List[str]) -> int:\n dp = [set()]\n\n for seq in sequences:\n chars = set(seq)\n\n if len(chars) < len(seq):\n continue\n\n dp.extend(chars | other for other in dp if not (chars & other))\n\n return max(map(len, dp))\n```\n\nIf you like this solution remember to **upvote it** to let me know.\n | 13 | You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**.
Return _the **maximum** possible length_ of `s`.
A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** arr = \[ "un ", "iq ", "ue "\]
**Output:** 4
**Explanation:** All the valid concatenations are:
- " "
- "un "
- "iq "
- "ue "
- "uniq " ( "un " + "iq ")
- "ique " ( "iq " + "ue ")
Maximum length is 4.
**Example 2:**
**Input:** arr = \[ "cha ", "r ", "act ", "ers "\]
**Output:** 6
**Explanation:** Possible longest valid concatenations are "chaers " ( "cha " + "ers ") and "acters " ( "act " + "ers ").
**Example 3:**
**Input:** arr = \[ "abcdefghijklmnopqrstuvwxyz "\]
**Output:** 26
**Explanation:** The only string in arr has all 26 characters.
**Constraints:**
* `1 <= arr.length <= 16`
* `1 <= arr[i].length <= 26`
* `arr[i]` contains only lowercase English letters. | For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1). |
Python Elegant & Short | DP | maximum-length-of-a-concatenated-string-with-unique-characters | 0 | 1 | ```\nclass Solution:\n """\n Time: O(n^2)\n Memory: O(n^2)\n """\n\n def maxLength(self, sequences: List[str]) -> int:\n dp = [set()]\n\n for seq in sequences:\n chars = set(seq)\n\n if len(chars) < len(seq):\n continue\n\n dp.extend(chars | other for other in dp if not (chars & other))\n\n return max(map(len, dp))\n```\n\nIf you like this solution remember to **upvote it** to let me know.\n | 13 | Write a program to count the number of days between two dates.
The two dates are given as strings, their format is `YYYY-MM-DD` as shown in the examples.
**Example 1:**
**Input:** date1 = "2019-06-29", date2 = "2019-06-30"
**Output:** 1
**Example 2:**
**Input:** date1 = "2020-01-15", date2 = "2019-12-31"
**Output:** 15
**Constraints:**
* The given dates are valid dates between the years `1971` and `2100`. | You can try all combinations and keep mask of characters you have. You can use DP. |
[Python3] Easy Understanding -- Bitmask + DFS | maximum-length-of-a-concatenated-string-with-unique-characters | 0 | 1 | ```\nclass Solution:\n def maxLength(self, arr: List[str]) -> int:\n arr_masks = []\n for s in arr:\n mask = 0\n uniq = True\n for c in s:\n shift = ord(c) - ord(\'a\')\n if (1 << shift) & mask == 0:\n mask |= (1 << shift)\n else:\n uniq = False\n break\n if uniq:\n arr_masks.append(mask)\n # print(list(map(lambda x: format(x, \'032b\'), arr_masks)))\n \n res = [0]\n mask = 0\n def dfs(idx, mask, item):\n if idx == len(arr_masks):\n # print(mask)\n res[0] = max(mask.bit_count(), res[0])\n return\n \n if arr_masks[idx] & mask == 0:\n # dfs(idx + 1, arr_masks[idx] & mask, item + [idx]) # TAKE BUGGG!\n dfs(idx + 1, arr_masks[idx] | mask, item + [idx]) # TAKE FIXX!\n dfs(idx + 1, mask, item) # No TAKE\n \n dfs(0, 0, [])\n \n return res[0]\n \n \n """ ========================= """\n n = len(arr) # ALSO AC, ref to lee215\n # res = set([])\n # dp = [set(arr[0])]\n dp = [set([])]\n for i in range(n):\n s = arr[i]\n set_s = set(s)\n if len(s) != len(set_s):\n continue\n for item in dp:\n if set_s & item:\n continue\n dp.append(item | set_s) # FIXXX!\n # item |= set_s # BUGGG!\n # dp.append(set_s) # BUGG\n # print(dp)\n return max(len(item) for item in dp)\n``` | 1 | You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**.
Return _the **maximum** possible length_ of `s`.
A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** arr = \[ "un ", "iq ", "ue "\]
**Output:** 4
**Explanation:** All the valid concatenations are:
- " "
- "un "
- "iq "
- "ue "
- "uniq " ( "un " + "iq ")
- "ique " ( "iq " + "ue ")
Maximum length is 4.
**Example 2:**
**Input:** arr = \[ "cha ", "r ", "act ", "ers "\]
**Output:** 6
**Explanation:** Possible longest valid concatenations are "chaers " ( "cha " + "ers ") and "acters " ( "act " + "ers ").
**Example 3:**
**Input:** arr = \[ "abcdefghijklmnopqrstuvwxyz "\]
**Output:** 26
**Explanation:** The only string in arr has all 26 characters.
**Constraints:**
* `1 <= arr.length <= 16`
* `1 <= arr[i].length <= 26`
* `arr[i]` contains only lowercase English letters. | For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1). |
[Python3] Easy Understanding -- Bitmask + DFS | maximum-length-of-a-concatenated-string-with-unique-characters | 0 | 1 | ```\nclass Solution:\n def maxLength(self, arr: List[str]) -> int:\n arr_masks = []\n for s in arr:\n mask = 0\n uniq = True\n for c in s:\n shift = ord(c) - ord(\'a\')\n if (1 << shift) & mask == 0:\n mask |= (1 << shift)\n else:\n uniq = False\n break\n if uniq:\n arr_masks.append(mask)\n # print(list(map(lambda x: format(x, \'032b\'), arr_masks)))\n \n res = [0]\n mask = 0\n def dfs(idx, mask, item):\n if idx == len(arr_masks):\n # print(mask)\n res[0] = max(mask.bit_count(), res[0])\n return\n \n if arr_masks[idx] & mask == 0:\n # dfs(idx + 1, arr_masks[idx] & mask, item + [idx]) # TAKE BUGGG!\n dfs(idx + 1, arr_masks[idx] | mask, item + [idx]) # TAKE FIXX!\n dfs(idx + 1, mask, item) # No TAKE\n \n dfs(0, 0, [])\n \n return res[0]\n \n \n """ ========================= """\n n = len(arr) # ALSO AC, ref to lee215\n # res = set([])\n # dp = [set(arr[0])]\n dp = [set([])]\n for i in range(n):\n s = arr[i]\n set_s = set(s)\n if len(s) != len(set_s):\n continue\n for item in dp:\n if set_s & item:\n continue\n dp.append(item | set_s) # FIXXX!\n # item |= set_s # BUGGG!\n # dp.append(set_s) # BUGG\n # print(dp)\n return max(len(item) for item in dp)\n``` | 1 | Write a program to count the number of days between two dates.
The two dates are given as strings, their format is `YYYY-MM-DD` as shown in the examples.
**Example 1:**
**Input:** date1 = "2019-06-29", date2 = "2019-06-30"
**Output:** 1
**Example 2:**
**Input:** date1 = "2020-01-15", date2 = "2019-12-31"
**Output:** 15
**Constraints:**
* The given dates are valid dates between the years `1971` and `2100`. | You can try all combinations and keep mask of characters you have. You can use DP. |
Python 3: DFS + Backtracking: Skyline, Fill the Bottom-Left Cell(s) First | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Intuition\n\nThe hardest part about this question is figuring out how you can efficiently try all of the combinations.\n\nThe second example in particular shows the difficulty - how do you make sure you try the size-1 square in the middle??\n\n## Strategy: "You Have to Start Somewhere"\n\nWhen in doubt, in these kinds of tiling and coverage problems, remember that *all cells must be filled*.\n\nThis includes the bottom-left unfilled cell!\n\nSo without loss of generality, we **try all squares that can fit whose bottom-left corner is at the bottom-left unfilled cell.**\n\n## ASCII Art\n\n```s\n7 x 8:\n\n0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0\n# 0 0 0 0 0 0 0 # is the bottom-left unfilled cell\n we can use sizes up to 7\n\n let\'s try 7!\n\n7 7 7 7 7 7 7 0\n7 7 7 7 7 7 7 0\n7 7 7 7 7 7 7 0\n7 7 7 7 7 7 7 0\n7 7 7 7 7 7 7 0\n7 7 7 7 7 7 7 0\n7 7 7 7 7 7 7 # # next bottom-left unfilled square\n\n long column: the rest of the 7 cells can\n only fit 1x1 squares.\n\n Total squares: a 7x7 square, and 7 1x1 squares. Total of 8\n```\n\nSo 7 let us fill a ton of cells, early, but doomed us to a very narrow remaining column that requires us to use a lot of 1x1 squares.\n\nWhat if we tried 4 first?\n\n```s\n\nTry a 4x4 first:\n\n0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0\n4 4 4 4 0 0 0 0\n4 4 4 4 0 0 0 0\n4 4 4 4 0 0 0 0\n4 4 4 4 # 0 0 0\n\nTry another 4x4\n\n0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0\n# 0 0 0 0 0 0 0\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n\nNow let\'s try the largest remaining square we can, 3x3\n\n3 3 3 0 0 0 0 0\n3 3 3 0 0 0 0 0\n3 3 3 # 0 0 0 0\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n\nAnd let\'s try another 3x3\n\n3 3 3 3 3 3 0 0\n3 3 3 3 3 3 0 0\n3 3 3 3 3 3 # 0\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n\nAnd finally we can cover the last 3x2 area with a 2x2 and two 1x1s.\n\nTotal squares:\n two 4x4\n two 3x3\n one 2x2\n two 1x1\n\n Seven!\n```\n\nSo we can see that we\'re doing **DFS + backtracking**:\n* **try a size**\n * **based on that square, fill in the rest of the board**\n* try another size\n * fill in the board again from there\n* .. etc.\n\n# Approach\n\n## Basics: DFS + Backtracking\n\nTo find the bottom-left empty cell, and make it easy, I noticed we can use a **"skyline" representation.** As we fill in the cells, we fill in from the bottom-left so there are no gaps between the bottom edge and the top of the filled squares. So I stored the `heights` of the filled area of each of the `m` columns.\n\nIn addition, I also store a current `count` of squares used thus far.\n\nTo find the bottom-left unfilled square, I find the minimum value `lo` in the skyline, then find the first column index `i` where that occurs.\n\nTo determine which square sizes we can use, I iterate to find the last contiguous location `j-1` where we have that height. Then `j-i` is the maximum width. `n - lo` is the max height. The max side length of a square is the `min` of these two.\n\n## Intermediate: Pruning\n\nThe problem with DFS + backtracking, as we know, is that it has factorial runtime in general because we\'re trying all combinations. That\'s obviously going to be horrible, and can give TLE.\n\nTherefore **we should "prune" DFS search branches**, i.e. return early without continuing if we know a particular sequence of early squares can\'t be the best solution.\n\n### Pruning 1: Only Consider Improvements\n\nIn the example above, the first DFS + backtracking solution we found was 8 squares. Therefore we know the answer is at *most* 8.\n\nThus we should not ever consider arrangements that have 7 or more squares without solving the problem. We need at least one more square, for at least 8, and therefore we can\'t improve on the solution.\n\n**So only keep working on subproblems with `count < best - 1`**\n\n### Pruning 2: Largest Cell First\n\nWe stop searching if we can\'t improve on the best, so we want to quickly get a reasonable upper bound on the answer. We don\'t want to fill the board with all 1x1 squares first, then try just one 2x2 square, and so on.\n\nAs a rough guess, we can assume that **starting with large squares is generally better.** It\'s clearly not optimal as the ASCII example shows, but it\'s close.\n\nTherefore we **try squares in order of largest size to smallest at all DFS levels**\n\n### Pruning 3: Shortcuts\n\nIn the first ASCII example, we can see that if we have a width-1 unfilled region, our only option is to use 1x1 squares. So we can reduce the depth of the stack by just adding all the 1x1 squares in one shot, intead of recursing for each 1x1.\n\nNote: this optimization is not featured here.\n\n## Advanced: Memoization\n\nIn principle we could detect when the remaining region is a `n\' x m\'` region where `n\' <= n` and `m\' <= m`. Such regions probably repeat themselves frequently in the search, especially narrow regions because we greedily fill squares.\n\nNote: this optimization is not in the code.\n\nNote 2: technically it *is* in the code, but it\'s commented out. It caused bugs. I\'m 99% sure it\'s because I used `global` as a sin of convenience. When you do that, I think the `global` is shared across the copies of the DFS function, and so the nested modifcations and caching caused problems.\n\n# Complexity\n- Time complexity: exponential?\n - the greedy solution will try the largest first, then the next largest, and so on to get a least upper bound quickly\n - so in practice the scaling probably isn\'t *horrible*, but the upper bound is likely not particularly tight\n - and we try all smaller squares, which means there are MANY ways to pick up that that number of squares without covering the area still\n - therefore I\'m going with exponential. The exponent is some function of `m` and `n` that scales better than `m+n` I think, but it\'s still exponential time\n\n- Space complexity: `O(max(m,n) log(min(m, n)))`?\n - since we use the greedy strategy we\'ll fill up a lot of cells with a square with side length `min(m+n)`. We\'ll keep doing that until there\'s a smaller region of size `smallerSide, largerSide % smallerSide` at the right edge. Then we\'ll repeat\n - if we subtracted all the largest-size squares at once (which we don\'t, but could do) then we\'re actually doing Euclid\'s GCD algorithm\n - that algorithm runs in `log(min(m, n))` steps\n - but we\'re not doing O(1) mod operations, we\'re subtracting each square individually. This takes O(max(m, n)) steps for the first round\n - later rounds can also take that amount of time worst case\n - so the greedy solution takes worst case `max(m,n)` time for each of `log(min(m, n))` "GCD" steps\n - this is the max steps, i.e. the max recursion depth. So this is the memory complexity\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n\n def tilingRectangle(self, n: int, m: int) -> int:\n # Weird problem, but I like it. Neat.\n\n # Current state while filling could be the "skyline," wlog pick an element to place as low as possible\n # and toward the left.\n\n # maybe the best is to look at the bottom row accordingly\n # can put an element up to the min side length\n # or anything less, then continue\n\n # DFS + backtracking could be good here. A greedy "go largest first" strategy\n # can give us a resonable upper bound on the answer, after which we can rule out\n # further square sizes\n\n # but 7 6 5 4 4 1 shows we have to be very careful about this\n \n # WLOG the bottom-most area, and the left-most as a tie-breaker, has to be filled. With an element starting at that corner.\n # So we can use that as the "launching point" for DFS + backtracking\n\n if m == n: return 1\n if m == 1: return n\n if n == 1: return m\n\n heights = [0]*m\n global best, count\n best = n*m # all 1x1\n count = 0\n\n def explore():\n global best, count\n\n # print(" "*count + f"{heights=}")\n\n # find the lowest level and its width\n lo = min(heights)\n\n if lo == n:\n best = min(count, best)\n # print(" "*count + f"new best! {best=}")\n return\n\n if count >= best-1:\n # need at least one more square, can\'t improve on best\n return\n\n i = heights.index(lo)\n j = i+1\n while j < m and heights[j] == lo: j += 1\n s = min(j-i, n-lo) # max side length\n \n #### THIS DOESN\'T WORK: CAUSES BUGS WITH NEGATIVE RECTANGLE COUNTS\n ## I think the reason is globals, there\'s only one global count for all calls.\n ## Result: small subproblem has small count, then we unwind the stack\n ## in the larger outer problem, resulting in a negative count\n # # # # if the remaining region is a rectangle, recurse with a exponentially simpler subproblem\n # if i == 0 and j == m and lo:\n # # print(f"{heights=}, {n-lo=}, {m=}")\n # # full width, shorter height\n # best = min(best, count + self.tilingRectangle(n-lo, m))\n # return\n\n # TODO: detect vertical rectangle - a lot less common though since we fill from bottom\n # example: if i == m-1, fill up to second-highest height\n\n\n for w in range(s, 0, -1):\n # consider a square of each possible width\n count += 1\n for c in range(i, i+w):\n heights[c] += w\n\n # print(" "*count + f"considering {w=}")\n explore()\n\n # backtrack\n count -= 1\n for c in range(i, i+w):\n heights[c] -= w\n\n explore()\n\n return best\n``` | 0 | Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_.
**Example 1:**
**Input:** n = 2, m = 3
**Output:** 3
**Explanation:** `3` squares are necessary to cover the rectangle.
`2` (squares of `1x1`)
`1` (square of `2x2`)
**Example 2:**
**Input:** n = 5, m = 8
**Output:** 5
**Example 3:**
**Input:** n = 11, m = 13
**Output:** 6
**Constraints:**
* `1 <= n, m <= 13` | Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m. |
Python 3: DFS + Backtracking: Skyline, Fill the Bottom-Left Cell(s) First | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Intuition\n\nThe hardest part about this question is figuring out how you can efficiently try all of the combinations.\n\nThe second example in particular shows the difficulty - how do you make sure you try the size-1 square in the middle??\n\n## Strategy: "You Have to Start Somewhere"\n\nWhen in doubt, in these kinds of tiling and coverage problems, remember that *all cells must be filled*.\n\nThis includes the bottom-left unfilled cell!\n\nSo without loss of generality, we **try all squares that can fit whose bottom-left corner is at the bottom-left unfilled cell.**\n\n## ASCII Art\n\n```s\n7 x 8:\n\n0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0\n# 0 0 0 0 0 0 0 # is the bottom-left unfilled cell\n we can use sizes up to 7\n\n let\'s try 7!\n\n7 7 7 7 7 7 7 0\n7 7 7 7 7 7 7 0\n7 7 7 7 7 7 7 0\n7 7 7 7 7 7 7 0\n7 7 7 7 7 7 7 0\n7 7 7 7 7 7 7 0\n7 7 7 7 7 7 7 # # next bottom-left unfilled square\n\n long column: the rest of the 7 cells can\n only fit 1x1 squares.\n\n Total squares: a 7x7 square, and 7 1x1 squares. Total of 8\n```\n\nSo 7 let us fill a ton of cells, early, but doomed us to a very narrow remaining column that requires us to use a lot of 1x1 squares.\n\nWhat if we tried 4 first?\n\n```s\n\nTry a 4x4 first:\n\n0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0\n4 4 4 4 0 0 0 0\n4 4 4 4 0 0 0 0\n4 4 4 4 0 0 0 0\n4 4 4 4 # 0 0 0\n\nTry another 4x4\n\n0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0\n# 0 0 0 0 0 0 0\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n\nNow let\'s try the largest remaining square we can, 3x3\n\n3 3 3 0 0 0 0 0\n3 3 3 0 0 0 0 0\n3 3 3 # 0 0 0 0\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n\nAnd let\'s try another 3x3\n\n3 3 3 3 3 3 0 0\n3 3 3 3 3 3 0 0\n3 3 3 3 3 3 # 0\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n4 4 4 4 4 4 4 4\n\nAnd finally we can cover the last 3x2 area with a 2x2 and two 1x1s.\n\nTotal squares:\n two 4x4\n two 3x3\n one 2x2\n two 1x1\n\n Seven!\n```\n\nSo we can see that we\'re doing **DFS + backtracking**:\n* **try a size**\n * **based on that square, fill in the rest of the board**\n* try another size\n * fill in the board again from there\n* .. etc.\n\n# Approach\n\n## Basics: DFS + Backtracking\n\nTo find the bottom-left empty cell, and make it easy, I noticed we can use a **"skyline" representation.** As we fill in the cells, we fill in from the bottom-left so there are no gaps between the bottom edge and the top of the filled squares. So I stored the `heights` of the filled area of each of the `m` columns.\n\nIn addition, I also store a current `count` of squares used thus far.\n\nTo find the bottom-left unfilled square, I find the minimum value `lo` in the skyline, then find the first column index `i` where that occurs.\n\nTo determine which square sizes we can use, I iterate to find the last contiguous location `j-1` where we have that height. Then `j-i` is the maximum width. `n - lo` is the max height. The max side length of a square is the `min` of these two.\n\n## Intermediate: Pruning\n\nThe problem with DFS + backtracking, as we know, is that it has factorial runtime in general because we\'re trying all combinations. That\'s obviously going to be horrible, and can give TLE.\n\nTherefore **we should "prune" DFS search branches**, i.e. return early without continuing if we know a particular sequence of early squares can\'t be the best solution.\n\n### Pruning 1: Only Consider Improvements\n\nIn the example above, the first DFS + backtracking solution we found was 8 squares. Therefore we know the answer is at *most* 8.\n\nThus we should not ever consider arrangements that have 7 or more squares without solving the problem. We need at least one more square, for at least 8, and therefore we can\'t improve on the solution.\n\n**So only keep working on subproblems with `count < best - 1`**\n\n### Pruning 2: Largest Cell First\n\nWe stop searching if we can\'t improve on the best, so we want to quickly get a reasonable upper bound on the answer. We don\'t want to fill the board with all 1x1 squares first, then try just one 2x2 square, and so on.\n\nAs a rough guess, we can assume that **starting with large squares is generally better.** It\'s clearly not optimal as the ASCII example shows, but it\'s close.\n\nTherefore we **try squares in order of largest size to smallest at all DFS levels**\n\n### Pruning 3: Shortcuts\n\nIn the first ASCII example, we can see that if we have a width-1 unfilled region, our only option is to use 1x1 squares. So we can reduce the depth of the stack by just adding all the 1x1 squares in one shot, intead of recursing for each 1x1.\n\nNote: this optimization is not featured here.\n\n## Advanced: Memoization\n\nIn principle we could detect when the remaining region is a `n\' x m\'` region where `n\' <= n` and `m\' <= m`. Such regions probably repeat themselves frequently in the search, especially narrow regions because we greedily fill squares.\n\nNote: this optimization is not in the code.\n\nNote 2: technically it *is* in the code, but it\'s commented out. It caused bugs. I\'m 99% sure it\'s because I used `global` as a sin of convenience. When you do that, I think the `global` is shared across the copies of the DFS function, and so the nested modifcations and caching caused problems.\n\n# Complexity\n- Time complexity: exponential?\n - the greedy solution will try the largest first, then the next largest, and so on to get a least upper bound quickly\n - so in practice the scaling probably isn\'t *horrible*, but the upper bound is likely not particularly tight\n - and we try all smaller squares, which means there are MANY ways to pick up that that number of squares without covering the area still\n - therefore I\'m going with exponential. The exponent is some function of `m` and `n` that scales better than `m+n` I think, but it\'s still exponential time\n\n- Space complexity: `O(max(m,n) log(min(m, n)))`?\n - since we use the greedy strategy we\'ll fill up a lot of cells with a square with side length `min(m+n)`. We\'ll keep doing that until there\'s a smaller region of size `smallerSide, largerSide % smallerSide` at the right edge. Then we\'ll repeat\n - if we subtracted all the largest-size squares at once (which we don\'t, but could do) then we\'re actually doing Euclid\'s GCD algorithm\n - that algorithm runs in `log(min(m, n))` steps\n - but we\'re not doing O(1) mod operations, we\'re subtracting each square individually. This takes O(max(m, n)) steps for the first round\n - later rounds can also take that amount of time worst case\n - so the greedy solution takes worst case `max(m,n)` time for each of `log(min(m, n))` "GCD" steps\n - this is the max steps, i.e. the max recursion depth. So this is the memory complexity\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n\n def tilingRectangle(self, n: int, m: int) -> int:\n # Weird problem, but I like it. Neat.\n\n # Current state while filling could be the "skyline," wlog pick an element to place as low as possible\n # and toward the left.\n\n # maybe the best is to look at the bottom row accordingly\n # can put an element up to the min side length\n # or anything less, then continue\n\n # DFS + backtracking could be good here. A greedy "go largest first" strategy\n # can give us a resonable upper bound on the answer, after which we can rule out\n # further square sizes\n\n # but 7 6 5 4 4 1 shows we have to be very careful about this\n \n # WLOG the bottom-most area, and the left-most as a tie-breaker, has to be filled. With an element starting at that corner.\n # So we can use that as the "launching point" for DFS + backtracking\n\n if m == n: return 1\n if m == 1: return n\n if n == 1: return m\n\n heights = [0]*m\n global best, count\n best = n*m # all 1x1\n count = 0\n\n def explore():\n global best, count\n\n # print(" "*count + f"{heights=}")\n\n # find the lowest level and its width\n lo = min(heights)\n\n if lo == n:\n best = min(count, best)\n # print(" "*count + f"new best! {best=}")\n return\n\n if count >= best-1:\n # need at least one more square, can\'t improve on best\n return\n\n i = heights.index(lo)\n j = i+1\n while j < m and heights[j] == lo: j += 1\n s = min(j-i, n-lo) # max side length\n \n #### THIS DOESN\'T WORK: CAUSES BUGS WITH NEGATIVE RECTANGLE COUNTS\n ## I think the reason is globals, there\'s only one global count for all calls.\n ## Result: small subproblem has small count, then we unwind the stack\n ## in the larger outer problem, resulting in a negative count\n # # # # if the remaining region is a rectangle, recurse with a exponentially simpler subproblem\n # if i == 0 and j == m and lo:\n # # print(f"{heights=}, {n-lo=}, {m=}")\n # # full width, shorter height\n # best = min(best, count + self.tilingRectangle(n-lo, m))\n # return\n\n # TODO: detect vertical rectangle - a lot less common though since we fill from bottom\n # example: if i == m-1, fill up to second-highest height\n\n\n for w in range(s, 0, -1):\n # consider a square of each possible width\n count += 1\n for c in range(i, i+w):\n heights[c] += w\n\n # print(" "*count + f"considering {w=}")\n explore()\n\n # backtrack\n count -= 1\n for c in range(i, i+w):\n heights[c] -= w\n\n explore()\n\n return best\n``` | 0 | You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree.
If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child.
Note that the nodes have no values and that we only use the node numbers in this problem.
**Example 1:**
**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,-1,-1,-1\]
**Output:** true
**Example 2:**
**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,3,-1,-1\]
**Output:** false
**Example 3:**
**Input:** n = 2, leftChild = \[1,0\], rightChild = \[-1,-1\]
**Output:** false
**Constraints:**
* `n == leftChild.length == rightChild.length`
* `1 <= n <= 104`
* `-1 <= leftChild[i], rightChild[i] <= n - 1` | Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m). |
Python skyline | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Approach\nKeep track of the right view skyline of the rectangle that we have filled with squares, which is represented by a heap of right sides of squares. Then iteratively take the leftmost rooftop and place a new square on it.\n\n# Code\n```\nimport heapq\n\nclass Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n self.answer = n * m\n\n def heappush_if_valid_side(skyline, x, y1, y2):\n if x < n and y2 > y1:\n heapq.heappush(skyline, (x, y1, y2))\n\n def heappop_glue_consecutive_sides(skyline):\n x, y1, y2 = heapq.heappop(skyline)\n while skyline and skyline[0][:2] == (x, y2):\n _, _, y2 = heapq.heappop(skyline)\n return x, y1, y2\n\n def dfs(skyline, n_rectangles):\n if not skyline:\n self.answer = min(self.answer, n_rectangles)\n if n_rectangles >= self.answer:\n return\n\n x, y1, y2 = heappop_glue_consecutive_sides(skyline)\n\n for side in range(min(n - x, y2 - y1), 0, -1):\n skyline_copy = skyline[:]\n heappush_if_valid_side(skyline_copy, x + side, y1, y1 + side)\n heappush_if_valid_side(skyline_copy, x, y1 + side, y2)\n dfs(skyline_copy, n_rectangles + 1)\n\n dfs(skyline=[(0, 0, m)], n_rectangles=0)\n return self.answer\n``` | 0 | Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_.
**Example 1:**
**Input:** n = 2, m = 3
**Output:** 3
**Explanation:** `3` squares are necessary to cover the rectangle.
`2` (squares of `1x1`)
`1` (square of `2x2`)
**Example 2:**
**Input:** n = 5, m = 8
**Output:** 5
**Example 3:**
**Input:** n = 11, m = 13
**Output:** 6
**Constraints:**
* `1 <= n, m <= 13` | Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m. |
Python skyline | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Approach\nKeep track of the right view skyline of the rectangle that we have filled with squares, which is represented by a heap of right sides of squares. Then iteratively take the leftmost rooftop and place a new square on it.\n\n# Code\n```\nimport heapq\n\nclass Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n self.answer = n * m\n\n def heappush_if_valid_side(skyline, x, y1, y2):\n if x < n and y2 > y1:\n heapq.heappush(skyline, (x, y1, y2))\n\n def heappop_glue_consecutive_sides(skyline):\n x, y1, y2 = heapq.heappop(skyline)\n while skyline and skyline[0][:2] == (x, y2):\n _, _, y2 = heapq.heappop(skyline)\n return x, y1, y2\n\n def dfs(skyline, n_rectangles):\n if not skyline:\n self.answer = min(self.answer, n_rectangles)\n if n_rectangles >= self.answer:\n return\n\n x, y1, y2 = heappop_glue_consecutive_sides(skyline)\n\n for side in range(min(n - x, y2 - y1), 0, -1):\n skyline_copy = skyline[:]\n heappush_if_valid_side(skyline_copy, x + side, y1, y1 + side)\n heappush_if_valid_side(skyline_copy, x, y1 + side, y2)\n dfs(skyline_copy, n_rectangles + 1)\n\n dfs(skyline=[(0, 0, m)], n_rectangles=0)\n return self.answer\n``` | 0 | You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree.
If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child.
Note that the nodes have no values and that we only use the node numbers in this problem.
**Example 1:**
**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,-1,-1,-1\]
**Output:** true
**Example 2:**
**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,3,-1,-1\]
**Output:** false
**Example 3:**
**Input:** n = 2, leftChild = \[1,0\], rightChild = \[-1,-1\]
**Output:** false
**Constraints:**
* `n == leftChild.length == rightChild.length`
* `1 <= n <= 104`
* `-1 <= leftChild[i], rightChild[i] <= n - 1` | Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m). |
Fast Python Solution | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Code\n```\nclass Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n if n == m: return 1\n depth = [0]*m\n \n def fn(x): \n """Explore tiling rectangle area via backtracking."""\n nonlocal ans \n if x < ans: \n if min(depth) == n: ans = x # all tiled\n else: \n i = min(depth)\n j = jj = depth.index(i) # (i, j)\n while jj < m and depth[jj] == depth[j]: jj += 1\n k = min(n - i, jj - j)\n for kk in reversed(range(1, k+1)): \n for jj in range(j, j+kk): depth[jj] += kk\n fn(x+1)\n for jj in range(j, j+kk): depth[jj] -= kk\n \n ans = max(n, m)\n fn(0)\n return ans \n``` | 0 | Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_.
**Example 1:**
**Input:** n = 2, m = 3
**Output:** 3
**Explanation:** `3` squares are necessary to cover the rectangle.
`2` (squares of `1x1`)
`1` (square of `2x2`)
**Example 2:**
**Input:** n = 5, m = 8
**Output:** 5
**Example 3:**
**Input:** n = 11, m = 13
**Output:** 6
**Constraints:**
* `1 <= n, m <= 13` | Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m. |
Fast Python Solution | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Code\n```\nclass Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n if n == m: return 1\n depth = [0]*m\n \n def fn(x): \n """Explore tiling rectangle area via backtracking."""\n nonlocal ans \n if x < ans: \n if min(depth) == n: ans = x # all tiled\n else: \n i = min(depth)\n j = jj = depth.index(i) # (i, j)\n while jj < m and depth[jj] == depth[j]: jj += 1\n k = min(n - i, jj - j)\n for kk in reversed(range(1, k+1)): \n for jj in range(j, j+kk): depth[jj] += kk\n fn(x+1)\n for jj in range(j, j+kk): depth[jj] -= kk\n \n ans = max(n, m)\n fn(0)\n return ans \n``` | 0 | You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree.
If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child.
Note that the nodes have no values and that we only use the node numbers in this problem.
**Example 1:**
**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,-1,-1,-1\]
**Output:** true
**Example 2:**
**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,3,-1,-1\]
**Output:** false
**Example 3:**
**Input:** n = 2, leftChild = \[1,0\], rightChild = \[-1,-1\]
**Output:** false
**Constraints:**
* `n == leftChild.length == rightChild.length`
* `1 <= n <= 104`
* `-1 <= leftChild[i], rightChild[i] <= n - 1` | Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m). |
Python backtrack solution | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrom hint, we can try backtrack, use a 2D array as board to record where already put rectangle on it, and search for empty space for new rectangle. but here we need some important optimization, otherwise it will go TLE.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. create a 2D m x n board to denote where already put a rectangle.\n2. search for first empty space to put rectangle, and always put rectangle right & bottom direction.\n3. IMPORTANT: we can find the largest rectangle can be put from this position, using r + offset & c + offset check (because we always put rectangle right & bottom direction). And we first put the largest rectangle, and then shrink block by block.\n3.1 Example: if largest is 4 x 4, then we first do 4 x 4, and then shrink row & col by 1, so we take away 4 + 3 = 7 blocks, and then do 3 x 3, and take away 3 + 2 = 5 blocks, etc. This way, we prevent flip every block all at once and flip them all back (16 for 4 x 4, 9 for 3 x 3, etc), and improve TC for this step from O(n^3) to O(n^2)\n4. just backtrack for best answer.\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 tilingRectangle(self, n: int, m: int) -> int:\n # try brute force backtracking?\n board = [[0 for _ in range(n)] for _ in range(m)]\n\n ans = math.inf\n def bt(counts):\n nonlocal ans\n if counts >= ans:\n return\n \n pos = None\n found = False\n for row in range(m):\n for col in range(n):\n if board[row][col] == 0:\n pos = (row, col)\n found = True\n break\n if found:\n break\n if not found:\n ans = min(ans, counts)\n return\n\n # see how many difference size of squares we can place from this spot\n r, c = pos\n offset = 0\n while r + offset < m and c + offset < n and board[r + offset][c] == 0 and board[r][c + offset] == 0:\n offset += 1\n # max can place size is offset\n for row in range(r, r + offset):\n for col in range(c, c + offset):\n board[row][col] = 1\n # do bt and shrink\n while offset > 0:\n bt(counts + 1)\n # shrink\n for row in range(r, r + offset):\n board[row][c + offset - 1] = 0\n for col in range(c, c + offset):\n board[r + offset - 1][col] = 0\n offset -= 1\n\n bt(0)\n return ans\n``` | 0 | Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_.
**Example 1:**
**Input:** n = 2, m = 3
**Output:** 3
**Explanation:** `3` squares are necessary to cover the rectangle.
`2` (squares of `1x1`)
`1` (square of `2x2`)
**Example 2:**
**Input:** n = 5, m = 8
**Output:** 5
**Example 3:**
**Input:** n = 11, m = 13
**Output:** 6
**Constraints:**
* `1 <= n, m <= 13` | Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m. |
Python backtrack solution | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrom hint, we can try backtrack, use a 2D array as board to record where already put rectangle on it, and search for empty space for new rectangle. but here we need some important optimization, otherwise it will go TLE.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. create a 2D m x n board to denote where already put a rectangle.\n2. search for first empty space to put rectangle, and always put rectangle right & bottom direction.\n3. IMPORTANT: we can find the largest rectangle can be put from this position, using r + offset & c + offset check (because we always put rectangle right & bottom direction). And we first put the largest rectangle, and then shrink block by block.\n3.1 Example: if largest is 4 x 4, then we first do 4 x 4, and then shrink row & col by 1, so we take away 4 + 3 = 7 blocks, and then do 3 x 3, and take away 3 + 2 = 5 blocks, etc. This way, we prevent flip every block all at once and flip them all back (16 for 4 x 4, 9 for 3 x 3, etc), and improve TC for this step from O(n^3) to O(n^2)\n4. just backtrack for best answer.\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 tilingRectangle(self, n: int, m: int) -> int:\n # try brute force backtracking?\n board = [[0 for _ in range(n)] for _ in range(m)]\n\n ans = math.inf\n def bt(counts):\n nonlocal ans\n if counts >= ans:\n return\n \n pos = None\n found = False\n for row in range(m):\n for col in range(n):\n if board[row][col] == 0:\n pos = (row, col)\n found = True\n break\n if found:\n break\n if not found:\n ans = min(ans, counts)\n return\n\n # see how many difference size of squares we can place from this spot\n r, c = pos\n offset = 0\n while r + offset < m and c + offset < n and board[r + offset][c] == 0 and board[r][c + offset] == 0:\n offset += 1\n # max can place size is offset\n for row in range(r, r + offset):\n for col in range(c, c + offset):\n board[row][col] = 1\n # do bt and shrink\n while offset > 0:\n bt(counts + 1)\n # shrink\n for row in range(r, r + offset):\n board[row][c + offset - 1] = 0\n for col in range(c, c + offset):\n board[r + offset - 1][col] = 0\n offset -= 1\n\n bt(0)\n return ans\n``` | 0 | You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree.
If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child.
Note that the nodes have no values and that we only use the node numbers in this problem.
**Example 1:**
**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,-1,-1,-1\]
**Output:** true
**Example 2:**
**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,3,-1,-1\]
**Output:** false
**Example 3:**
**Input:** n = 2, leftChild = \[1,0\], rightChild = \[-1,-1\]
**Output:** false
**Constraints:**
* `n == leftChild.length == rightChild.length`
* `1 <= n <= 104`
* `-1 <= leftChild[i], rightChild[i] <= n - 1` | Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m). |
Bottom Up Approach utilizing Transpose and minimal siding speed up | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTiling approach can be solved in limited looping with memoization. Seems brutish, but this is actually one of the better ways to solve this it turns out (cool links on tessalation on wiki for this). Two edge cases to consider, namely that the 11x13 square is a break in the systematic ordering, so if you run into a version of it you\'ll need to break out. Otherwise, if you have a situation of a square as a rectangle, can return 1 early. Similar occurrences happen in the processing of the problem. \n\nProcessing approach follows \nBy looping over the measure of n and m in a nested fashion, we trace out every sub rectangle that could be created. If we are at an instance of a square in our sub rectangles, we know one square will cover it. If we are at an inbound location that we have already mapped, we can skip this portion, effectively halving our work. Otherwise, we will need to determine the sub rectangles and min rectangle assortment for our offset options. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe will keep a memo of our measure results of rectangles overall. \nLoop over the n_measure (size of our shape space in distance n) and loop over the m_measure (size of our shape space in distance m). If we are at an equal measure part, memoize one square for this portion and continue. Otherwise if we are at a point in measurement and we have the matching alternate (transpose position), we can use the stored result and continue. For all others, we will need to then loop over our offset options on our minimal side and find the minimal shaping. Our final result for this will be the square needed to cover our current positioning and the sub rectangles minimal amount. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nWe loop n/2 and m/2 by the transpose operations. We then loop our offset over the minimal of the current measure of n and m. This gives a run time of O((n/2) * (m/2) * min(n, m))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nWe do end up storing n*m valuations, so we need O(n * m) space. \n\n\n# Code\n```\nclass Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n # edge case 1 allowing early quit processing. \n if n == m : \n return 1 \n # edge case 2, occurs according to tiling problem. Only one for which implementation breaks. \n elif (n==11 and m == 13) or (n==13 and m==11) : \n return 6 \n else : \n # memo usage of results. Build from result 1 go to end result. Bottom up progression. \n memo = [[0 for _ in range(m+1)] for _ in range(n+1)]\n # loop from 1 to n inclusive \n for n_measure in range(1, n+1) : \n # loop 1 to m inclusive \n for m_measure in range(1, m+1) : \n # if we are at equal measures, this is a square \n if (n_measure == m_measure) : \n # mark it as 1 as these are our measures so this can be covered by equal square \n memo[n_measure][m_measure] = 1\n continue\n # only do half the array \n else : \n if m_measure < n and n_measure < m and memo[m_measure][n_measure] != 0 : \n memo[n_measure][m_measure] = memo[m_measure][n_measure]\n continue\n # otherwise, set sub rectangles 1 and 2 and minimal rectangle to infinity to start \n sub_rectangle1, sub_rectangle2, min_rectangle = inf, inf, inf\n offset = 1 \n # starting with offset of 1 go to min of n and m \n while offset <= min(n_measure, m_measure) : \n # if we have run off the smaller, break at this point \n if (m_measure - offset < 0) or (n_measure - offset < 0) : \n break\n # get sub rectangles 1 and 2 based off of which slicing you\'re doing \n sub_rectangle1 = memo[n_measure][m_measure-offset] + memo[n_measure-offset][offset]\n sub_rectangle2 = memo[n_measure-offset][m_measure] + memo[offset][m_measure-offset]\n # set min to minimum of the results now built \n min_rectangle = min(min_rectangle, sub_rectangle1, sub_rectangle2)\n # increment offset as if you are doing two different measures simultaneously \n offset += 1 \n # memoize current result minmal plus 1 more for work done for this square itself. \n memo[n_measure][m_measure] = min_rectangle + 1\n return memo[n][m]\n``` | 0 | Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_.
**Example 1:**
**Input:** n = 2, m = 3
**Output:** 3
**Explanation:** `3` squares are necessary to cover the rectangle.
`2` (squares of `1x1`)
`1` (square of `2x2`)
**Example 2:**
**Input:** n = 5, m = 8
**Output:** 5
**Example 3:**
**Input:** n = 11, m = 13
**Output:** 6
**Constraints:**
* `1 <= n, m <= 13` | Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m. |
Bottom Up Approach utilizing Transpose and minimal siding speed up | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTiling approach can be solved in limited looping with memoization. Seems brutish, but this is actually one of the better ways to solve this it turns out (cool links on tessalation on wiki for this). Two edge cases to consider, namely that the 11x13 square is a break in the systematic ordering, so if you run into a version of it you\'ll need to break out. Otherwise, if you have a situation of a square as a rectangle, can return 1 early. Similar occurrences happen in the processing of the problem. \n\nProcessing approach follows \nBy looping over the measure of n and m in a nested fashion, we trace out every sub rectangle that could be created. If we are at an instance of a square in our sub rectangles, we know one square will cover it. If we are at an inbound location that we have already mapped, we can skip this portion, effectively halving our work. Otherwise, we will need to determine the sub rectangles and min rectangle assortment for our offset options. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe will keep a memo of our measure results of rectangles overall. \nLoop over the n_measure (size of our shape space in distance n) and loop over the m_measure (size of our shape space in distance m). If we are at an equal measure part, memoize one square for this portion and continue. Otherwise if we are at a point in measurement and we have the matching alternate (transpose position), we can use the stored result and continue. For all others, we will need to then loop over our offset options on our minimal side and find the minimal shaping. Our final result for this will be the square needed to cover our current positioning and the sub rectangles minimal amount. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nWe loop n/2 and m/2 by the transpose operations. We then loop our offset over the minimal of the current measure of n and m. This gives a run time of O((n/2) * (m/2) * min(n, m))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nWe do end up storing n*m valuations, so we need O(n * m) space. \n\n\n# Code\n```\nclass Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n # edge case 1 allowing early quit processing. \n if n == m : \n return 1 \n # edge case 2, occurs according to tiling problem. Only one for which implementation breaks. \n elif (n==11 and m == 13) or (n==13 and m==11) : \n return 6 \n else : \n # memo usage of results. Build from result 1 go to end result. Bottom up progression. \n memo = [[0 for _ in range(m+1)] for _ in range(n+1)]\n # loop from 1 to n inclusive \n for n_measure in range(1, n+1) : \n # loop 1 to m inclusive \n for m_measure in range(1, m+1) : \n # if we are at equal measures, this is a square \n if (n_measure == m_measure) : \n # mark it as 1 as these are our measures so this can be covered by equal square \n memo[n_measure][m_measure] = 1\n continue\n # only do half the array \n else : \n if m_measure < n and n_measure < m and memo[m_measure][n_measure] != 0 : \n memo[n_measure][m_measure] = memo[m_measure][n_measure]\n continue\n # otherwise, set sub rectangles 1 and 2 and minimal rectangle to infinity to start \n sub_rectangle1, sub_rectangle2, min_rectangle = inf, inf, inf\n offset = 1 \n # starting with offset of 1 go to min of n and m \n while offset <= min(n_measure, m_measure) : \n # if we have run off the smaller, break at this point \n if (m_measure - offset < 0) or (n_measure - offset < 0) : \n break\n # get sub rectangles 1 and 2 based off of which slicing you\'re doing \n sub_rectangle1 = memo[n_measure][m_measure-offset] + memo[n_measure-offset][offset]\n sub_rectangle2 = memo[n_measure-offset][m_measure] + memo[offset][m_measure-offset]\n # set min to minimum of the results now built \n min_rectangle = min(min_rectangle, sub_rectangle1, sub_rectangle2)\n # increment offset as if you are doing two different measures simultaneously \n offset += 1 \n # memoize current result minmal plus 1 more for work done for this square itself. \n memo[n_measure][m_measure] = min_rectangle + 1\n return memo[n][m]\n``` | 0 | You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree.
If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child.
Note that the nodes have no values and that we only use the node numbers in this problem.
**Example 1:**
**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,-1,-1,-1\]
**Output:** true
**Example 2:**
**Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,3,-1,-1\]
**Output:** false
**Example 3:**
**Input:** n = 2, leftChild = \[1,0\], rightChild = \[-1,-1\]
**Output:** false
**Constraints:**
* `n == leftChild.length == rightChild.length`
* `1 <= n <= 104`
* `-1 <= leftChild[i], rightChild[i] <= n - 1` | Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m). |
Simply Simple Python Solution - with detailed explanation | minimum-swaps-to-make-strings-equal | 0 | 1 | In this problem, we just need to find the count of different characters in both strings. When I use "x_y" i.e. I have x in s1 at index i and y in s2 at same index i. Similary "y_x" means I have y in s1 at index j and x in s2 at same index j. \n\n#### Example 1:\ns1 = "xx"\ns2 = "yy"\n\nif we iterate through both string and keep checking every index, we get two indexes with different values in both s1 and s2:\n"x_y" at index 0 and "x_y" at index 1.\nif we have 2 "x_y" then we only need 1 swap to make them equal. Swap x at index 0 in s1 with y at index 1 in s2.\n\n#### Example 2:\ns1 = "yy"\ns2 = "xx"\n\nHere also we have 2 different values: "y_x" at index 0 and "y_x" at index 1. so it will also take 1 swap to make them equal.\n\n#### Example 3:\ns1 = "xy"\ns2 = "yx"\n\nHere we have one count of "x_y" at index 0 and one count of "y_x" at index 1. We need 2 swaps to make these indexes equal.\nSwap s1[0] and s2[0], s1 = "yy", s2 = "xx".\nSwap s1[0] and s2[1], s1 = "xy", s2 = "xy".\n\n#### Example 4:\ns1 = "xxyyxyxyxx", \ns2 = "xyyxyxxxyx"\n\nFirst remove the indexes with same characters:\ns1 = "xyxyyx"\ns2 = "yxyxxy"\n\n"x_y" count = 3 (index 0, 2, 5)\n"y_x" count = 3 (index 1, 3, 4)\n\nindex 0 and 2 can be made equal in just 1 swap. see Example 1.\nindex 1 and 3 can also be made equal in just 1 swap. see Example 2.\n\nindex 5 and 4 can be made Equal in 2 swaps. see Example 3\n\nso we only need 4 swaps.\n\n### Steps:\n1. Get the count of "x_y" and "y_x"\n2. If sum of both counts is odd then return -1. We need a pair to make the strings equal\n3. Each 2 count of "x_y" needs just 1 swap. So add half of "x_y" count to the result\n4. Each 2 count of "y_x" needs just 1 swap. So add half of "y_x" count to the result\n5. if we still have 1 count of "x_y" and 1 count of "y_x" then they need 2 swaps so add 2 in result.\n\n```\ndef minimumSwap(self, s1: str, s2: str) -> int:\n x_y, y_x = 0, 0\n for c1, c2 in zip(s1, s2):\n if c1 != c2:\n if c1 == \'x\':\n x_y += 1\n else:\n y_x += 1\n \n if (x_y + y_x) % 2 == 1:\n return -1\n # Both x_y and y_x count shall either be even or odd to get the result.\n\t\t# x_y + y_x should be even\n \n res = x_y // 2\n res += y_x // 2\n \n if x_y % 2 == 1:\n res += 2\n # If there count is odd i.e. we have "xy" and "yx" situation\n # so we need 2 more swaps to make them equal\n \n return res\n```\n | 200 | You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`.
Return the minimum number of swaps required to make `s1` and `s2` equal, or return `-1` if it is impossible to do so.
**Example 1:**
**Input:** s1 = "xx ", s2 = "yy "
**Output:** 1
**Explanation:** Swap s1\[0\] and s2\[1\], s1 = "yx ", s2 = "yx ".
**Example 2:**
**Input:** s1 = "xy ", s2 = "yx "
**Output:** 2
**Explanation:** Swap s1\[0\] and s2\[0\], s1 = "yy ", s2 = "xx ".
Swap s1\[0\] and s2\[1\], s1 = "xy ", s2 = "xy ".
Note that you cannot swap s1\[0\] and s1\[1\] to make s1 equal to "yx ", cause we can only swap chars in different strings.
**Example 3:**
**Input:** s1 = "xx ", s2 = "xy "
**Output:** -1
**Constraints:**
* `1 <= s1.length, s2.length <= 1000`
* `s1.length == s2.length`
* `s1, s2` only contain `'x'` or `'y'`. | Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors. |
85% O(n) TC and 81% O(1) SC easy python solution | minimum-swaps-to-make-strings-equal | 0 | 1 | ```\ndef minimumSwap(self, s1: str, s2: str) -> int:\n\txy = yx = 0\n\tfor i in range(len(s1)):\n\t\tif(s1[i] == "x" and s2[i] == "y"):\n\t\t\txy += 1\n\t\tif(s2[i] == "x" and s1[i] == "y"):\n\t\t\tyx += 1\n\tif(xy%2 ^ yx%2):\n\t\treturn -1\n\tans = xy//2 + yx//2 + (xy%2) * 2\n\treturn ans\n``` | 1 | You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`.
Return the minimum number of swaps required to make `s1` and `s2` equal, or return `-1` if it is impossible to do so.
**Example 1:**
**Input:** s1 = "xx ", s2 = "yy "
**Output:** 1
**Explanation:** Swap s1\[0\] and s2\[1\], s1 = "yx ", s2 = "yx ".
**Example 2:**
**Input:** s1 = "xy ", s2 = "yx "
**Output:** 2
**Explanation:** Swap s1\[0\] and s2\[0\], s1 = "yy ", s2 = "xx ".
Swap s1\[0\] and s2\[1\], s1 = "xy ", s2 = "xy ".
Note that you cannot swap s1\[0\] and s1\[1\] to make s1 equal to "yx ", cause we can only swap chars in different strings.
**Example 3:**
**Input:** s1 = "xx ", s2 = "xy "
**Output:** -1
**Constraints:**
* `1 <= s1.length, s2.length <= 1000`
* `s1.length == s2.length`
* `s1, s2` only contain `'x'` or `'y'`. | Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors. |
python 3 || simple greedy solution || O(n)/O(1) | minimum-swaps-to-make-strings-equal | 0 | 1 | ```\nclass Solution:\n def minimumSwap(self, s1: str, s2: str) -> int:\n xy = yx = 0\n for c1, c2 in zip(s1, s2):\n if c1 == \'x\' and c2 == \'y\':\n xy += 1\n elif c1 == \'y\' and c2 == \'x\':\n yx += 1\n \n if (xy + yx) % 2:\n return -1\n \n return xy // 2 + yx // 2 + (xy % 2) * 2 | 1 | You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`.
Return the minimum number of swaps required to make `s1` and `s2` equal, or return `-1` if it is impossible to do so.
**Example 1:**
**Input:** s1 = "xx ", s2 = "yy "
**Output:** 1
**Explanation:** Swap s1\[0\] and s2\[1\], s1 = "yx ", s2 = "yx ".
**Example 2:**
**Input:** s1 = "xy ", s2 = "yx "
**Output:** 2
**Explanation:** Swap s1\[0\] and s2\[0\], s1 = "yy ", s2 = "xx ".
Swap s1\[0\] and s2\[1\], s1 = "xy ", s2 = "xy ".
Note that you cannot swap s1\[0\] and s1\[1\] to make s1 equal to "yx ", cause we can only swap chars in different strings.
**Example 3:**
**Input:** s1 = "xx ", s2 = "xy "
**Output:** -1
**Constraints:**
* `1 <= s1.length, s2.length <= 1000`
* `s1.length == s2.length`
* `s1, s2` only contain `'x'` or `'y'`. | Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors. |
Python 3: Count Pairs | minimum-swaps-to-make-strings-equal | 0 | 1 | # Intuition\n\nI took a long time to fix this, probably would have failed an interview question if I only had 20 minutes with no hints :(\n\nAnyway, after some failed attempts I first realized tha the rules of swapping mean we don\'t care about where the indices `i` and `j` are, just that they\'re in different strings.\n\nI also eventually realized we can probably ignore any indices where the two strings match.\n\nExample problem:\n```s\nxxyyxyxyxx\nxyyxyxxxyx\n\nignore indices where they don\'t match\n\nxyxyyx\nyxyxxy\n\nswapping doesn\'t matter where i,j are, just that\nthe indices are in different strings and they don\'t match\n\nxxxyyy\nyyyxxx\n```\n\nIn every pair of characters with the same kind of mismatch (e.g. xy here)\n```\nxx\nyy\n```\nwe can see that we can fix both in one swap: move the last x and first y to get\n```\nxy\nxy\n```\n\nSo we can count the `xy` mismatches and `yx` mismatches, and divide by two to get the number of swaps.\n\nThis leaves either\n* nothing\n* a single pair, yx or xy\n* or two opposize pairs like this:\n```\nxy\nyx\n```\n\n**Nothing left:** no more swaps, done.\n\n**Single pair:** there\'s no way to balance the strings, return -1\n\n**Two opposite pairs:** the fastest fix is to make two swaps.\n\n# Approach\n\nI count up the number of `xy` mismatches and `yx` mismatches.\n\nThe answer is mostly `ans = xy//2 + yx//2`.\n\nThen some final logic handles the last two, if any, or returning -1:\n* if `xy == yx == 0` then return `ans`\n* if `xy == yx == 1` then return `ans + 2` to account for the last swap\n* otherwise `xy` xor `yx` is 1, and the other is zero. Return -1 because we can\'t do the swap.\n\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(1)\n\n# Side Note\n\nThis is the first question I\'ve seen where the input complexities lie! Almost always on LC, two inputs of size 1e3 mean we have an O(N^2) algorithm expected of us. But not here!\n\n# Code\n```\nclass Solution:\n def minimumSwap(self, s1: str, s2: str) -> int:\n \n # for matches: ignore them, only look at mismatched indices\n # we have have xy mismatches and yx mismatches\n\n # xyxyyx => rules don\'t care about where i and j are, just that they exist\n # yxyxxy\n\n # xyxyyy => for pairs of xy mismatches: swap second x with first y xx/yy => xy/xy => fixed\n # xyyxxx\n\n # so xxxyyy\n # yyyxxx => fix 2 xy mismatches in one swap\n\n # two swaps later:\n # xy\n # yx # first two indices fixed with a swap, and same with last two\n\n # then we\'re left with a reorder at the end: two swaps\n\n xy = 0\n yx = 0\n for c1, c2 in zip(s1, s2):\n if c1 == \'x\' and c2 == \'y\':\n xy += 1\n elif c1 == \'y\' and c2 == \'x\':\n yx += 1\n\n ans = xy//2 + yx//2\n xy %= 2\n yx %= 2\n\n if xy == yx: # both 0 or 1; if 1 we need to do a final swap in two ops\n return ans + (2 if xy else 0)\n else:\n # we have x/y or y/x, no swap possible\n return -1\n``` | 0 | You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`.
Return the minimum number of swaps required to make `s1` and `s2` equal, or return `-1` if it is impossible to do so.
**Example 1:**
**Input:** s1 = "xx ", s2 = "yy "
**Output:** 1
**Explanation:** Swap s1\[0\] and s2\[1\], s1 = "yx ", s2 = "yx ".
**Example 2:**
**Input:** s1 = "xy ", s2 = "yx "
**Output:** 2
**Explanation:** Swap s1\[0\] and s2\[0\], s1 = "yy ", s2 = "xx ".
Swap s1\[0\] and s2\[1\], s1 = "xy ", s2 = "xy ".
Note that you cannot swap s1\[0\] and s1\[1\] to make s1 equal to "yx ", cause we can only swap chars in different strings.
**Example 3:**
**Input:** s1 = "xx ", s2 = "xy "
**Output:** -1
**Constraints:**
* `1 <= s1.length, s2.length <= 1000`
* `s1.length == s2.length`
* `s1, s2` only contain `'x'` or `'y'`. | Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors. |
✅counting solution || python | minimum-swaps-to-make-strings-equal | 0 | 1 | \n# Code\n```\nclass Solution:\n def minimumSwap(self, s1: str, s2: str) -> int:\n cx1=0\n cx2=0\n for i in s1:\n if(i==\'x\'):cx1+=1\n for i in s2:\n if(i==\'x\'):cx2+=1\n if((cx1+cx2)%2!=0):return -1\n cx1=0\n cx2=0\n for i in range(len(s1)):\n if(s1[i]==s2[i]):continue\n elif(s1[i]==\'x\'):cx1+=1\n else: cx2+=1\n ans=0\n ans+=(cx1//2)\n ans+=(cx2//2)\n if(cx1%2):ans+=1\n if(cx2%2):ans+=1\n return ans\n \n``` | 0 | You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`.
Return the minimum number of swaps required to make `s1` and `s2` equal, or return `-1` if it is impossible to do so.
**Example 1:**
**Input:** s1 = "xx ", s2 = "yy "
**Output:** 1
**Explanation:** Swap s1\[0\] and s2\[1\], s1 = "yx ", s2 = "yx ".
**Example 2:**
**Input:** s1 = "xy ", s2 = "yx "
**Output:** 2
**Explanation:** Swap s1\[0\] and s2\[0\], s1 = "yy ", s2 = "xx ".
Swap s1\[0\] and s2\[1\], s1 = "xy ", s2 = "xy ".
Note that you cannot swap s1\[0\] and s1\[1\] to make s1 equal to "yx ", cause we can only swap chars in different strings.
**Example 3:**
**Input:** s1 = "xx ", s2 = "xy "
**Output:** -1
**Constraints:**
* `1 <= s1.length, s2.length <= 1000`
* `s1.length == s2.length`
* `s1, s2` only contain `'x'` or `'y'`. | Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors. |
Easy Solution | count-number-of-nice-subarrays | 0 | 1 | # Code\n```\nclass Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n ans = 0\n helper = [-1] + [i for i, el in enumerate(nums) if el % 2] + [len(nums)]\n\n for i in range(1, len(helper) - k):\n ans += (helper[i] - helper[i - 1]) * (helper[i + k] - helper[i + k - 1])\n\n return ans\n``` | 2 | Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it.
Return _the number of **nice** sub-arrays_.
**Example 1:**
**Input:** nums = \[1,1,2,1,1\], k = 3
**Output:** 2
**Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] and \[1,2,1,1\].
**Example 2:**
**Input:** nums = \[2,4,6\], k = 1
**Output:** 0
**Explanation:** There is no odd numbers in the array.
**Example 3:**
**Input:** nums = \[2,2,2,1,2,2,1,2,2,2\], k = 2
**Output:** 16
**Constraints:**
* `1 <= nums.length <= 50000`
* `1 <= nums[i] <= 10^5`
* `1 <= k <= nums.length` | The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x? |
Easy Solution | count-number-of-nice-subarrays | 0 | 1 | # Code\n```\nclass Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n ans = 0\n helper = [-1] + [i for i, el in enumerate(nums) if el % 2] + [len(nums)]\n\n for i in range(1, len(helper) - k):\n ans += (helper[i] - helper[i - 1]) * (helper[i + k] - helper[i + k - 1])\n\n return ans\n``` | 2 | You are given a string `s`. Reorder the string using the following algorithm:
1. Pick the **smallest** character from `s` and **append** it to the result.
2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it.
3. Repeat step 2 until you cannot pick more characters.
4. Pick the **largest** character from `s` and **append** it to the result.
5. Pick the **largest** character from `s` which is smaller than the last appended character to the result and **append** it.
6. Repeat step 5 until you cannot pick more characters.
7. Repeat the steps from 1 to 6 until you pick all characters from `s`.
In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.
Return _the result string after sorting_ `s` _with this algorithm_.
**Example 1:**
**Input:** s = "aaaabbbbcccc "
**Output:** "abccbaabccba "
**Explanation:** After steps 1, 2 and 3 of the first iteration, result = "abc "
After steps 4, 5 and 6 of the first iteration, result = "abccba "
First iteration is done. Now s = "aabbcc " and we go back to step 1
After steps 1, 2 and 3 of the second iteration, result = "abccbaabc "
After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba "
**Example 2:**
**Input:** s = "rat "
**Output:** "art "
**Explanation:** The word "rat " becomes "art " after re-ordering it with the mentioned algorithm.
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of only lowercase English letters. | After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.