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 |
---|---|---|---|---|---|---|---|
4 lines code in python | make-two-arrays-equal-by-reversing-subarrays | 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 canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n target.sort(reverse=True)\n arr.sort(reverse=True)\n if target==arr:\n return True\n else:\n return False\n``` | 1 | You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.
Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_.
**Example 1:**
**Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\]
**Output:** true
**Explanation:** You can follow the next steps to convert arr to target:
1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\]
2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\]
3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\]
There are multiple ways to convert arr to target, this is not the only way to do so.
**Example 2:**
**Input:** target = \[7\], arr = \[7\]
**Output:** true
**Explanation:** arr is equal to target without any reverses.
**Example 3:**
**Input:** target = \[3,7,9\], arr = \[3,7,11\]
**Output:** false
**Explanation:** arr does not have value 9 and it can never be converted to target.
**Constraints:**
* `target.length == arr.length`
* `1 <= target.length <= 1000`
* `1 <= target[i] <= 1000`
* `1 <= arr[i] <= 1000` | For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c. |
Python3 || Easy solution | make-two-arrays-equal-by-reversing-subarrays | 0 | 1 | please upvote if you find the solution helpful.\n\n# Code\n```\nclass Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n return sorted(target) == sorted(arr)\n``` | 1 | You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.
Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_.
**Example 1:**
**Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\]
**Output:** true
**Explanation:** You can follow the next steps to convert arr to target:
1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\]
2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\]
3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\]
There are multiple ways to convert arr to target, this is not the only way to do so.
**Example 2:**
**Input:** target = \[7\], arr = \[7\]
**Output:** true
**Explanation:** arr is equal to target without any reverses.
**Example 3:**
**Input:** target = \[3,7,9\], arr = \[3,7,11\]
**Output:** false
**Explanation:** arr does not have value 9 and it can never be converted to target.
**Constraints:**
* `target.length == arr.length`
* `1 <= target.length <= 1000`
* `1 <= target[i] <= 1000`
* `1 <= arr[i] <= 1000` | For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c. |
one line code | make-two-arrays-equal-by-reversing-subarrays | 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:50%\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:100%\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n return sorted(target)==sorted(arr)\n``` | 2 | You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.
Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_.
**Example 1:**
**Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\]
**Output:** true
**Explanation:** You can follow the next steps to convert arr to target:
1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\]
2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\]
3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\]
There are multiple ways to convert arr to target, this is not the only way to do so.
**Example 2:**
**Input:** target = \[7\], arr = \[7\]
**Output:** true
**Explanation:** arr is equal to target without any reverses.
**Example 3:**
**Input:** target = \[3,7,9\], arr = \[3,7,11\]
**Output:** false
**Explanation:** arr does not have value 9 and it can never be converted to target.
**Constraints:**
* `target.length == arr.length`
* `1 <= target.length <= 1000`
* `1 <= target[i] <= 1000`
* `1 <= arr[i] <= 1000` | For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c. |
Simple [Python O(N)] Solution | make-two-arrays-equal-by-reversing-subarrays | 0 | 1 | # Intuition JUET\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach brute force\nin this problem first cheak len of target and arr if not equal return False and and if target and arr are equal return True\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:wrost case: O(nlog n)\n- best case : 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 canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n if len(target)!=len(arr):\n return False\n for i in target:\n if i not in arr:\n return False\n target.sort()\n arr.sort()\n for i in range(len(arr)):\n if arr[i]!= target[i]:\n return False\n return True\n``` | 1 | You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.
Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_.
**Example 1:**
**Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\]
**Output:** true
**Explanation:** You can follow the next steps to convert arr to target:
1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\]
2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\]
3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\]
There are multiple ways to convert arr to target, this is not the only way to do so.
**Example 2:**
**Input:** target = \[7\], arr = \[7\]
**Output:** true
**Explanation:** arr is equal to target without any reverses.
**Example 3:**
**Input:** target = \[3,7,9\], arr = \[3,7,11\]
**Output:** false
**Explanation:** arr does not have value 9 and it can never be converted to target.
**Constraints:**
* `target.length == arr.length`
* `1 <= target.length <= 1000`
* `1 <= target[i] <= 1000`
* `1 <= arr[i] <= 1000` | For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c. |
Easy solution using dictionary in python | make-two-arrays-equal-by-reversing-subarrays | 0 | 1 | \n```\nclass Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n n, m = len(target), len(arr)\n if m > n:\n return False\n t = Counter(target)\n a = Counter(arr)\n for k, v in a.items():\n if k in t and v == t[k]:\n continue\n else:\n return False\n return True\n``` | 11 | You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.
Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_.
**Example 1:**
**Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\]
**Output:** true
**Explanation:** You can follow the next steps to convert arr to target:
1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\]
2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\]
3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\]
There are multiple ways to convert arr to target, this is not the only way to do so.
**Example 2:**
**Input:** target = \[7\], arr = \[7\]
**Output:** true
**Explanation:** arr is equal to target without any reverses.
**Example 3:**
**Input:** target = \[3,7,9\], arr = \[3,7,11\]
**Output:** false
**Explanation:** arr does not have value 9 and it can never be converted to target.
**Constraints:**
* `target.length == arr.length`
* `1 <= target.length <= 1000`
* `1 <= target[i] <= 1000`
* `1 <= arr[i] <= 1000` | For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c. |
Python easy solution without using sort, used HashMap, beats 80% in runtime | make-two-arrays-equal-by-reversing-subarrays | 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 canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n d = {}\n res = True\n for i in target:\n if i in d:\n d[i] += 1\n else:\n d[i] = 1\n\n for i in arr:\n if i in d:\n d[i] -= 1\n \n for k, v in d.items():\n if v > 0:\n res = False\n break\n return res\n \n \n``` | 1 | You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.
Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_.
**Example 1:**
**Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\]
**Output:** true
**Explanation:** You can follow the next steps to convert arr to target:
1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\]
2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\]
3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\]
There are multiple ways to convert arr to target, this is not the only way to do so.
**Example 2:**
**Input:** target = \[7\], arr = \[7\]
**Output:** true
**Explanation:** arr is equal to target without any reverses.
**Example 3:**
**Input:** target = \[3,7,9\], arr = \[3,7,11\]
**Output:** false
**Explanation:** arr does not have value 9 and it can never be converted to target.
**Constraints:**
* `target.length == arr.length`
* `1 <= target.length <= 1000`
* `1 <= target[i] <= 1000`
* `1 <= arr[i] <= 1000` | For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c. |
Python one line | 2 solution | make-two-arrays-equal-by-reversing-subarrays | 0 | 1 | **Python :**\n\n**1.** Using collecions.Counter\n**Time complexity :** *O(n)*\n**Space complexity :** *O(n)*\n\n```\ndef canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n\treturn Counter(arr) == Counter(target)\n```\n\n**1.** Sorting the arrays and compare\n**Time complexity :** *O(nlogn)*\n**Space complexity :** *O(1)*\n\n```\ndef canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n\treturn sorted(arr) == sorted(target)\n```\n\n**Like it ? please upvote !** | 8 | You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.
Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_.
**Example 1:**
**Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\]
**Output:** true
**Explanation:** You can follow the next steps to convert arr to target:
1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\]
2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\]
3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\]
There are multiple ways to convert arr to target, this is not the only way to do so.
**Example 2:**
**Input:** target = \[7\], arr = \[7\]
**Output:** true
**Explanation:** arr is equal to target without any reverses.
**Example 3:**
**Input:** target = \[3,7,9\], arr = \[3,7,11\]
**Output:** false
**Explanation:** arr does not have value 9 and it can never be converted to target.
**Constraints:**
* `target.length == arr.length`
* `1 <= target.length <= 1000`
* `1 <= target[i] <= 1000`
* `1 <= arr[i] <= 1000` | For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c. |
Python Counter 1liner | make-two-arrays-equal-by-reversing-subarrays | 0 | 1 | ```\nclass Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n \n return Counter(arr) == Counter(target)\n``` | 2 | You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.
Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_.
**Example 1:**
**Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\]
**Output:** true
**Explanation:** You can follow the next steps to convert arr to target:
1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\]
2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\]
3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\]
There are multiple ways to convert arr to target, this is not the only way to do so.
**Example 2:**
**Input:** target = \[7\], arr = \[7\]
**Output:** true
**Explanation:** arr is equal to target without any reverses.
**Example 3:**
**Input:** target = \[3,7,9\], arr = \[3,7,11\]
**Output:** false
**Explanation:** arr does not have value 9 and it can never be converted to target.
**Constraints:**
* `target.length == arr.length`
* `1 <= target.length <= 1000`
* `1 <= target[i] <= 1000`
* `1 <= arr[i] <= 1000` | For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c. |
Make Two Arrays Equal by Reversing Sub-arrays | make-two-arrays-equal-by-reversing-subarrays | 0 | 1 | # python 3 solution :******\n\n```\nclass Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n x = {}\n for i in target:\n if i in x :\n x[i]+=1\n else:\n x[i]=1\n for i in arr:\n if x.get(i):\n if x[i]<=0:\n return False\n x[i]-=1\n else:\n return False\n return True\n``` | 1 | You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.
Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_.
**Example 1:**
**Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\]
**Output:** true
**Explanation:** You can follow the next steps to convert arr to target:
1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\]
2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\]
3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\]
There are multiple ways to convert arr to target, this is not the only way to do so.
**Example 2:**
**Input:** target = \[7\], arr = \[7\]
**Output:** true
**Explanation:** arr is equal to target without any reverses.
**Example 3:**
**Input:** target = \[3,7,9\], arr = \[3,7,11\]
**Output:** false
**Explanation:** arr does not have value 9 and it can never be converted to target.
**Constraints:**
* `target.length == arr.length`
* `1 <= target.length <= 1000`
* `1 <= target[i] <= 1000`
* `1 <= arr[i] <= 1000` | For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c. |
Python 3 fast, no sort, no Counter | make-two-arrays-equal-by-reversing-subarrays | 0 | 1 | Runtime: 68 ms, faster than 99.60% of Python3 online submissions for Make Two Arrays Equal by Reversing Sub-arrays.\nMemory Usage: 14.2 MB, less than 10.31% of Python3 online submissions for Make Two Arrays Equal by Reversing Sub-arrays.\n\n```python\nclass Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n\n count = [0] * 1001\n\n for i in range(len(arr)):\n count[arr[i]] += 1\n count[target[i]] -= 1\n\n return not any(count)\n``` | 11 | You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.
Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_.
**Example 1:**
**Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\]
**Output:** true
**Explanation:** You can follow the next steps to convert arr to target:
1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\]
2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\]
3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\]
There are multiple ways to convert arr to target, this is not the only way to do so.
**Example 2:**
**Input:** target = \[7\], arr = \[7\]
**Output:** true
**Explanation:** arr is equal to target without any reverses.
**Example 3:**
**Input:** target = \[3,7,9\], arr = \[3,7,11\]
**Output:** false
**Explanation:** arr does not have value 9 and it can never be converted to target.
**Constraints:**
* `target.length == arr.length`
* `1 <= target.length <= 1000`
* `1 <= target[i] <= 1000`
* `1 <= arr[i] <= 1000` | For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c. |
✅ Python || 2 Easy || One liner with explanation | check-if-a-string-contains-all-binary-codes-of-size-k | 0 | 1 | 1. ### **Hashset**\nThe problem description states:\n```\nreturn true if every binary code of length k is a substring of s\n```\n\nSo it\'s not asking us to generate all valid binary code of length `k` from scratch. The main idea here is to check if all the substrings that can be formed from the input `s` is a complete set. For this validation, we can just count the number of combinations that can be formed using input `s` and then compare it with the required number of combinations. Here you can apply simple combinations formula to get the required number. In this case, where the number of characters available is 2(`0` and `1`) and the code length is `k`, the formula for finding the required number of combinations is **2 ^ k**.\neg: \n```\nwhen k = 2, then number of combinations is 2^k = 4 i.e {\'00\', \'11\', \'01\', \'10\'}\n```\n\nBelow is the code implementation for above approach:\n```\nclass Solution:\n def hasAllCodes(self, s: str, k: int) -> bool: \n return len({s[i:i+k] for i in range(len(s)-k+1)}) == 2 ** k \n```\n\nThe above code requires to find all the possible combinations in input `s` first before comparing with required count. This can be improved a bit more with the following approach which will kill the loop once it meets the required count:\n\n```\nclass Solution:\n def hasAllCodes(self, s: str, k: int) -> bool: \n n=len(s)\n required_count=2 ** k \n seen=set()\n for i in range(n-k+1):\n tmp=s[i:i+k]\n if tmp not in seen:\n seen.add(tmp)\n required_count-=1\n if required_count==0: # kill the loop once the condition is met\n return True\n return False \n```\n\n**Time - O(nk)** - Time required to iterate through all the characters of input `s` and `O(k)` is needed to calculate the hash of each subtring of length `k`.\n**Space - O(nk)**- space for storing the set of all substrings.\n\n---\n2. ### **Rolling Hash**\n\nThe previous approach has a downside and that is it calculates the hashcode of each substring with each iteration which accounts for **O(k)** time. This can be greatly reduced as we shift by only character with each iteration. So we will be using the concept of rolling hash which will shift the hashcode by only 1 bit with each iteration and mark it has seen hashcode. This post explains this concept in detail-> [Rolling Hash Explanation](https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/2092553/Explaining-the-Rolling-Hash-Method-or-Guide).\n\nThis approach reduces the Time but increases the space complexity as it has to create a list to store all possible hashcodes.\n\nBelow is my implementation using **Rolling hash**:\n```\nclass Solution:\n def hasAllCodes(self, s: str, k: int) -> bool: \n required_count=1<<k # same as 2 ^ k\n seen=[False] * required_count\n mask=required_count-1\n hash_code=0\n \n for i in range(len(s)):\n hash_code = ((hash_code<<1) & mask) | (int(s[i]))\n if i>=k-1 and not seen[hash_code]:\n seen[hash_code]=True\n required_count-=1\n if required_count==0:\n return True\n \n return False \n```\n\nA slight modification in the 2nd approach\'s way of storing the `seen` hash codes. Here in this implementation, the code will be using a `bitset` array instead of `boolean` array. Each bitset value in the array wil represent a 32-bit chunk of the required combinations range. This is just an alternative that I thought of while thinking of using `bitset`. It doesn\'t help in reducing space complexity.\n\n```\nclass Solution:\n def hasAllCodes(self, s: str, k: int) -> bool: \n required_count=1<<k \n seen=[0] * ((required_count-1)//32+1)\n mask=required_count-1\n hash_code=0\n \n def is_set(code):\n idx = code//32\n bit_pos = code%32 \n return seen[idx] & (1<<bit_pos) != 0\n \n def set_bit(code):\n idx = code//32\n bit_pos = code%32 \n seen[idx] |= (1<<bit_pos)\n \n for i in range(len(s)):\n hash_code = ((hash_code<<1) & mask) | (int(s[i]))\n if i>=k-1 and not is_set(hash_code):\n set_bit(hash_code)\n required_count-=1\n if required_count==0:\n return True\n \n return False \n```\n\n**Time - O(n)** - Time required to iterate through all the characters of input `s`.\n**Space - O(2^k)**- space for the storing the seen hash codes.\n\n---\n\n**Please upvote if you find it useful** | 26 | Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`.
**Example 1:**
**Input:** s = "00110110 ", k = 2
**Output:** true
**Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.
**Example 2:**
**Input:** s = "0110 ", k = 1
**Output:** true
**Explanation:** The binary codes of length 1 are "0 " and "1 ", it is clear that both exist as a substring.
**Example 3:**
**Input:** s = "0110 ", k = 2
**Output:** false
**Explanation:** The binary code "00 " is of length 2 and does not exist in the array.
**Constraints:**
* `1 <= s.length <= 5 * 105`
* `s[i]` is either `'0'` or `'1'`.
* `1 <= k <= 20` | Use the permutation and combination theory to add one (P, D) pair each time until n pairs. |
✅ Python || 2 Easy || One liner with explanation | check-if-a-string-contains-all-binary-codes-of-size-k | 0 | 1 | 1. ### **Hashset**\nThe problem description states:\n```\nreturn true if every binary code of length k is a substring of s\n```\n\nSo it\'s not asking us to generate all valid binary code of length `k` from scratch. The main idea here is to check if all the substrings that can be formed from the input `s` is a complete set. For this validation, we can just count the number of combinations that can be formed using input `s` and then compare it with the required number of combinations. Here you can apply simple combinations formula to get the required number. In this case, where the number of characters available is 2(`0` and `1`) and the code length is `k`, the formula for finding the required number of combinations is **2 ^ k**.\neg: \n```\nwhen k = 2, then number of combinations is 2^k = 4 i.e {\'00\', \'11\', \'01\', \'10\'}\n```\n\nBelow is the code implementation for above approach:\n```\nclass Solution:\n def hasAllCodes(self, s: str, k: int) -> bool: \n return len({s[i:i+k] for i in range(len(s)-k+1)}) == 2 ** k \n```\n\nThe above code requires to find all the possible combinations in input `s` first before comparing with required count. This can be improved a bit more with the following approach which will kill the loop once it meets the required count:\n\n```\nclass Solution:\n def hasAllCodes(self, s: str, k: int) -> bool: \n n=len(s)\n required_count=2 ** k \n seen=set()\n for i in range(n-k+1):\n tmp=s[i:i+k]\n if tmp not in seen:\n seen.add(tmp)\n required_count-=1\n if required_count==0: # kill the loop once the condition is met\n return True\n return False \n```\n\n**Time - O(nk)** - Time required to iterate through all the characters of input `s` and `O(k)` is needed to calculate the hash of each subtring of length `k`.\n**Space - O(nk)**- space for storing the set of all substrings.\n\n---\n2. ### **Rolling Hash**\n\nThe previous approach has a downside and that is it calculates the hashcode of each substring with each iteration which accounts for **O(k)** time. This can be greatly reduced as we shift by only character with each iteration. So we will be using the concept of rolling hash which will shift the hashcode by only 1 bit with each iteration and mark it has seen hashcode. This post explains this concept in detail-> [Rolling Hash Explanation](https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/2092553/Explaining-the-Rolling-Hash-Method-or-Guide).\n\nThis approach reduces the Time but increases the space complexity as it has to create a list to store all possible hashcodes.\n\nBelow is my implementation using **Rolling hash**:\n```\nclass Solution:\n def hasAllCodes(self, s: str, k: int) -> bool: \n required_count=1<<k # same as 2 ^ k\n seen=[False] * required_count\n mask=required_count-1\n hash_code=0\n \n for i in range(len(s)):\n hash_code = ((hash_code<<1) & mask) | (int(s[i]))\n if i>=k-1 and not seen[hash_code]:\n seen[hash_code]=True\n required_count-=1\n if required_count==0:\n return True\n \n return False \n```\n\nA slight modification in the 2nd approach\'s way of storing the `seen` hash codes. Here in this implementation, the code will be using a `bitset` array instead of `boolean` array. Each bitset value in the array wil represent a 32-bit chunk of the required combinations range. This is just an alternative that I thought of while thinking of using `bitset`. It doesn\'t help in reducing space complexity.\n\n```\nclass Solution:\n def hasAllCodes(self, s: str, k: int) -> bool: \n required_count=1<<k \n seen=[0] * ((required_count-1)//32+1)\n mask=required_count-1\n hash_code=0\n \n def is_set(code):\n idx = code//32\n bit_pos = code%32 \n return seen[idx] & (1<<bit_pos) != 0\n \n def set_bit(code):\n idx = code//32\n bit_pos = code%32 \n seen[idx] |= (1<<bit_pos)\n \n for i in range(len(s)):\n hash_code = ((hash_code<<1) & mask) | (int(s[i]))\n if i>=k-1 and not is_set(hash_code):\n set_bit(hash_code)\n required_count-=1\n if required_count==0:\n return True\n \n return False \n```\n\n**Time - O(n)** - Time required to iterate through all the characters of input `s`.\n**Space - O(2^k)**- space for the storing the seen hash codes.\n\n---\n\n**Please upvote if you find it useful** | 26 | Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.
Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
**Example 1:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,5\],\[3,4\],\[4,2\]\]
**Output:** \[0,3\]
**Explanation:** It's not possible to reach all the nodes from a single vertex. From 0 we can reach \[0,1,2,5\]. From 3 we can reach \[3,4,2,5\]. So we output \[0,3\].
**Example 2:**
**Input:** n = 5, edges = \[\[0,1\],\[2,1\],\[3,1\],\[1,4\],\[2,4\]\]
**Output:** \[0,2,3\]
**Explanation:** Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.
**Constraints:**
* `2 <= n <= 10^5`
* `1 <= edges.length <= min(10^5, n * (n - 1) / 2)`
* `edges[i].length == 2`
* `0 <= fromi, toi < n`
* All pairs `(fromi, toi)` are distinct. | We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k. |
[Python] 4 lines, O(N*k), with explanation | check-if-a-string-contains-all-binary-codes-of-size-k | 0 | 1 | This problem statement was incorrect during the contest. We want to find out if **ALL** "binary codes" of length `k` can be found (contiguously) in the string `s`.\n\nSo, for\n`k=1` , we need to find `0` and `1` in `s`. There are 2 binary codes.\n`k=2`, we need to find `00`, `01`, `10`, `11`. There are 4 binary codes.\n`k=3`, we need to find `000`, `001`, `011`, `010`, `100`, `101`, `110`, `111`. There are 8 binary codes.\n\nAnd now we\'ve found a pattern. The amount of binary codes we need to find in `s` is equal to `2 ** k`.\n\nIterate through `s`, and take a chunk of length `k`. Add it to a set. Once we\'re done, if `len(codes) == 2 ** k` we can return `True`.\n\n```\nclass Solution:\n def hasAllCodes(self, s: str, k: int) -> bool:\n codes = set()\n for i in range(len(s) - k + 1):\n codes.add(s[i:i+k])\n return len(codes) == 2 ** k\n```\n\n\n | 30 | Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`.
**Example 1:**
**Input:** s = "00110110 ", k = 2
**Output:** true
**Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.
**Example 2:**
**Input:** s = "0110 ", k = 1
**Output:** true
**Explanation:** The binary codes of length 1 are "0 " and "1 ", it is clear that both exist as a substring.
**Example 3:**
**Input:** s = "0110 ", k = 2
**Output:** false
**Explanation:** The binary code "00 " is of length 2 and does not exist in the array.
**Constraints:**
* `1 <= s.length <= 5 * 105`
* `s[i]` is either `'0'` or `'1'`.
* `1 <= k <= 20` | Use the permutation and combination theory to add one (P, D) pair each time until n pairs. |
[Python] 4 lines, O(N*k), with explanation | check-if-a-string-contains-all-binary-codes-of-size-k | 0 | 1 | This problem statement was incorrect during the contest. We want to find out if **ALL** "binary codes" of length `k` can be found (contiguously) in the string `s`.\n\nSo, for\n`k=1` , we need to find `0` and `1` in `s`. There are 2 binary codes.\n`k=2`, we need to find `00`, `01`, `10`, `11`. There are 4 binary codes.\n`k=3`, we need to find `000`, `001`, `011`, `010`, `100`, `101`, `110`, `111`. There are 8 binary codes.\n\nAnd now we\'ve found a pattern. The amount of binary codes we need to find in `s` is equal to `2 ** k`.\n\nIterate through `s`, and take a chunk of length `k`. Add it to a set. Once we\'re done, if `len(codes) == 2 ** k` we can return `True`.\n\n```\nclass Solution:\n def hasAllCodes(self, s: str, k: int) -> bool:\n codes = set()\n for i in range(len(s) - k + 1):\n codes.add(s[i:i+k])\n return len(codes) == 2 ** k\n```\n\n\n | 30 | Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.
Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
**Example 1:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,5\],\[3,4\],\[4,2\]\]
**Output:** \[0,3\]
**Explanation:** It's not possible to reach all the nodes from a single vertex. From 0 we can reach \[0,1,2,5\]. From 3 we can reach \[3,4,2,5\]. So we output \[0,3\].
**Example 2:**
**Input:** n = 5, edges = \[\[0,1\],\[2,1\],\[3,1\],\[1,4\],\[2,4\]\]
**Output:** \[0,2,3\]
**Explanation:** Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.
**Constraints:**
* `2 <= n <= 10^5`
* `1 <= edges.length <= min(10^5, n * (n - 1) / 2)`
* `edges[i].length == 2`
* `0 <= fromi, toi < n`
* All pairs `(fromi, toi)` are distinct. | We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k. |
Python, one-liner | check-if-a-string-contains-all-binary-codes-of-size-k | 0 | 1 | ```\nclass Solution:\n def hasAllCodes(self, s: str, k: int) -> bool:\n return len(set(s[i:i+k] for i in range(len(s)-k+1))) == 2**k\n``` | 11 | Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`.
**Example 1:**
**Input:** s = "00110110 ", k = 2
**Output:** true
**Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.
**Example 2:**
**Input:** s = "0110 ", k = 1
**Output:** true
**Explanation:** The binary codes of length 1 are "0 " and "1 ", it is clear that both exist as a substring.
**Example 3:**
**Input:** s = "0110 ", k = 2
**Output:** false
**Explanation:** The binary code "00 " is of length 2 and does not exist in the array.
**Constraints:**
* `1 <= s.length <= 5 * 105`
* `s[i]` is either `'0'` or `'1'`.
* `1 <= k <= 20` | Use the permutation and combination theory to add one (P, D) pair each time until n pairs. |
Python, one-liner | check-if-a-string-contains-all-binary-codes-of-size-k | 0 | 1 | ```\nclass Solution:\n def hasAllCodes(self, s: str, k: int) -> bool:\n return len(set(s[i:i+k] for i in range(len(s)-k+1))) == 2**k\n``` | 11 | Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`.
Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
**Example 1:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,5\],\[3,4\],\[4,2\]\]
**Output:** \[0,3\]
**Explanation:** It's not possible to reach all the nodes from a single vertex. From 0 we can reach \[0,1,2,5\]. From 3 we can reach \[3,4,2,5\]. So we output \[0,3\].
**Example 2:**
**Input:** n = 5, edges = \[\[0,1\],\[2,1\],\[3,1\],\[1,4\],\[2,4\]\]
**Output:** \[0,2,3\]
**Explanation:** Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.
**Constraints:**
* `2 <= n <= 10^5`
* `1 <= edges.length <= min(10^5, n * (n - 1) / 2)`
* `edges[i].length == 2`
* `0 <= fromi, toi < n`
* All pairs `(fromi, toi)` are distinct. | We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k. |
SIMPLE PYTHON SOLUTION | course-schedule-iv | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTOPOLOGICAL SORT\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:$$O(V*ElogE)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(V*E)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def checkIfPrerequisite(self, n: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n indegree=[0]*n\n adj=[[] for _ in range(n)]\n for i,j in prerequisites:\n adj[i].append(j)\n indegree[j]+=1\n st=[]\n for i in range(n):\n if indegree[i]==0:\n st.append(i)\n ans=[[] for _ in range(n)]\n while st:\n x=st.pop(0)\n for i in adj[x]:\n for j in ans[x]:\n if j not in ans[i]:\n ans[i].append(j)\n ans[i].append(x)\n indegree[i]-=1\n if indegree[i]==0:\n st.append(i)\n lst=[]\n for i,j in queries:\n if i in ans[j]:\n lst.append(True)\n else:\n lst.append(False)\n return lst\n``` | 1 | There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take course `bi`.
* For example, the pair `[0, 1]` indicates that you have to take course `0` before you can take course `1`.
Prerequisites can also be **indirect**. If course `a` is a prerequisite of course `b`, and course `b` is a prerequisite of course `c`, then course `a` is a prerequisite of course `c`.
You are also given an array `queries` where `queries[j] = [uj, vj]`. For the `jth` query, you should answer whether course `uj` is a prerequisite of course `vj` or not.
Return _a boolean array_ `answer`_, where_ `answer[j]` _is the answer to the_ `jth` _query._
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\], queries = \[\[0,1\],\[1,0\]\]
**Output:** \[false,true\]
**Explanation:** The pair \[1, 0\] indicates that you have to take course 1 before you can take course 0.
Course 0 is not a prerequisite of course 1, but the opposite is true.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\], queries = \[\[1,0\],\[0,1\]\]
**Output:** \[false,false\]
**Explanation:** There are no prerequisites, and each course is independent.
**Example 3:**
**Input:** numCourses = 3, prerequisites = \[\[1,2\],\[1,0\],\[2,0\]\], queries = \[\[1,0\],\[1,2\]\]
**Output:** \[true,true\]
**Constraints:**
* `2 <= numCourses <= 100`
* `0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)`
* `prerequisites[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* All the pairs `[ai, bi]` are **unique**.
* The prerequisites graph has no cycles.
* `1 <= queries.length <= 104`
* `0 <= ui, vi <= n - 1`
* `ui != vi` | null |
SIMPLE PYTHON SOLUTION | course-schedule-iv | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTOPOLOGICAL SORT\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:$$O(V*ElogE)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(V*E)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def checkIfPrerequisite(self, n: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n indegree=[0]*n\n adj=[[] for _ in range(n)]\n for i,j in prerequisites:\n adj[i].append(j)\n indegree[j]+=1\n st=[]\n for i in range(n):\n if indegree[i]==0:\n st.append(i)\n ans=[[] for _ in range(n)]\n while st:\n x=st.pop(0)\n for i in adj[x]:\n for j in ans[x]:\n if j not in ans[i]:\n ans[i].append(j)\n ans[i].append(x)\n indegree[i]-=1\n if indegree[i]==0:\n st.append(i)\n lst=[]\n for i,j in queries:\n if i in ans[j]:\n lst.append(True)\n else:\n lst.append(False)\n return lst\n``` | 1 | You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function:
You want to use the modify function to covert `arr` to `nums` using the minimum number of calls.
Return _the minimum number of function calls to make_ `nums` _from_ `arr`.
The test cases are generated so that the answer fits in a **32-bit** signed integer.
**Example 1:**
**Input:** nums = \[1,5\]
**Output:** 5
**Explanation:** Increment by 1 (second element): \[0, 0\] to get \[0, 1\] (1 operation).
Double all the elements: \[0, 1\] -> \[0, 2\] -> \[0, 4\] (2 operations).
Increment by 1 (both elements) \[0, 4\] -> \[1, 4\] -> **\[1, 5\]** (2 operations).
Total of operations: 1 + 2 + 2 = 5.
**Example 2:**
**Input:** nums = \[2,2\]
**Output:** 3
**Explanation:** Increment by 1 (both elements) \[0, 0\] -> \[0, 1\] -> \[1, 1\] (2 operations).
Double all the elements: \[1, 1\] -> **\[2, 2\]** (1 operation).
Total of operations: 2 + 1 = 3.
**Example 3:**
**Input:** nums = \[4,2,5\]
**Output:** 6
**Explanation:** (initial)\[0,0,0\] -> \[1,0,0\] -> \[1,0,1\] -> \[2,0,2\] -> \[2,1,2\] -> \[4,2,4\] -> **\[4,2,5\]**(nums).
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109` | Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array. |
Python-Easy to understand Topological sort , beats 100% | course-schedule-iv | 0 | 1 | # If you find it useful, please upvote it so that others can find it easily.\n# Complexity\n- Time complexity:\no(n(p+n)q)\n# please upvote if found helpful\n# Code\n```\nclass Solution(object):\n def checkIfPrerequisite(self, numCourses, prerequisites, queries):\n adj={i:[] for i in range(numCourses)}\n\n for x,y in prerequisites:\n adj[y].append(x)\n res=[]\n def dfs(crs):\n if crs not in premap:\n premap[crs]=set()\n for nei in adj[crs]:\n premap[crs]|=dfs(nei)\n premap[crs].add(crs)\n return premap[crs]\n\n premap={}\n for i in range(numCourses):\n dfs(i) \n for x,y in queries:\n res.append(x in premap[y])\n return res\n#please upvote if found helpful\n \n \n``` | 6 | There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take course `bi`.
* For example, the pair `[0, 1]` indicates that you have to take course `0` before you can take course `1`.
Prerequisites can also be **indirect**. If course `a` is a prerequisite of course `b`, and course `b` is a prerequisite of course `c`, then course `a` is a prerequisite of course `c`.
You are also given an array `queries` where `queries[j] = [uj, vj]`. For the `jth` query, you should answer whether course `uj` is a prerequisite of course `vj` or not.
Return _a boolean array_ `answer`_, where_ `answer[j]` _is the answer to the_ `jth` _query._
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\], queries = \[\[0,1\],\[1,0\]\]
**Output:** \[false,true\]
**Explanation:** The pair \[1, 0\] indicates that you have to take course 1 before you can take course 0.
Course 0 is not a prerequisite of course 1, but the opposite is true.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\], queries = \[\[1,0\],\[0,1\]\]
**Output:** \[false,false\]
**Explanation:** There are no prerequisites, and each course is independent.
**Example 3:**
**Input:** numCourses = 3, prerequisites = \[\[1,2\],\[1,0\],\[2,0\]\], queries = \[\[1,0\],\[1,2\]\]
**Output:** \[true,true\]
**Constraints:**
* `2 <= numCourses <= 100`
* `0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)`
* `prerequisites[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* All the pairs `[ai, bi]` are **unique**.
* The prerequisites graph has no cycles.
* `1 <= queries.length <= 104`
* `0 <= ui, vi <= n - 1`
* `ui != vi` | null |
Python-Easy to understand Topological sort , beats 100% | course-schedule-iv | 0 | 1 | # If you find it useful, please upvote it so that others can find it easily.\n# Complexity\n- Time complexity:\no(n(p+n)q)\n# please upvote if found helpful\n# Code\n```\nclass Solution(object):\n def checkIfPrerequisite(self, numCourses, prerequisites, queries):\n adj={i:[] for i in range(numCourses)}\n\n for x,y in prerequisites:\n adj[y].append(x)\n res=[]\n def dfs(crs):\n if crs not in premap:\n premap[crs]=set()\n for nei in adj[crs]:\n premap[crs]|=dfs(nei)\n premap[crs].add(crs)\n return premap[crs]\n\n premap={}\n for i in range(numCourses):\n dfs(i) \n for x,y in queries:\n res.append(x in premap[y])\n return res\n#please upvote if found helpful\n \n \n``` | 6 | You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function:
You want to use the modify function to covert `arr` to `nums` using the minimum number of calls.
Return _the minimum number of function calls to make_ `nums` _from_ `arr`.
The test cases are generated so that the answer fits in a **32-bit** signed integer.
**Example 1:**
**Input:** nums = \[1,5\]
**Output:** 5
**Explanation:** Increment by 1 (second element): \[0, 0\] to get \[0, 1\] (1 operation).
Double all the elements: \[0, 1\] -> \[0, 2\] -> \[0, 4\] (2 operations).
Increment by 1 (both elements) \[0, 4\] -> \[1, 4\] -> **\[1, 5\]** (2 operations).
Total of operations: 1 + 2 + 2 = 5.
**Example 2:**
**Input:** nums = \[2,2\]
**Output:** 3
**Explanation:** Increment by 1 (both elements) \[0, 0\] -> \[0, 1\] -> \[1, 1\] (2 operations).
Double all the elements: \[1, 1\] -> **\[2, 2\]** (1 operation).
Total of operations: 2 + 1 = 3.
**Example 3:**
**Input:** nums = \[4,2,5\]
**Output:** 6
**Explanation:** (initial)\[0,0,0\] -> \[1,0,0\] -> \[1,0,1\] -> \[2,0,2\] -> \[2,1,2\] -> \[4,2,4\] -> **\[4,2,5\]**(nums).
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109` | Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array. |
python3 recursion + memoization | course-schedule-iv | 0 | 1 | \n\n# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n\n @cache\n def check(n,target):\n nonlocal d\n if n == target:\n return True\n \n for e in d[n]:\n if check(e,target):\n return True\n\n return False\n\n\n res = []\n d = defaultdict(list)\n for x,y in prerequisites:\n d[x].append(y)\n for x,y in queries:\n res.append(check(x,y))\n \n return res\n``` | 1 | There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take course `bi`.
* For example, the pair `[0, 1]` indicates that you have to take course `0` before you can take course `1`.
Prerequisites can also be **indirect**. If course `a` is a prerequisite of course `b`, and course `b` is a prerequisite of course `c`, then course `a` is a prerequisite of course `c`.
You are also given an array `queries` where `queries[j] = [uj, vj]`. For the `jth` query, you should answer whether course `uj` is a prerequisite of course `vj` or not.
Return _a boolean array_ `answer`_, where_ `answer[j]` _is the answer to the_ `jth` _query._
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\], queries = \[\[0,1\],\[1,0\]\]
**Output:** \[false,true\]
**Explanation:** The pair \[1, 0\] indicates that you have to take course 1 before you can take course 0.
Course 0 is not a prerequisite of course 1, but the opposite is true.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\], queries = \[\[1,0\],\[0,1\]\]
**Output:** \[false,false\]
**Explanation:** There are no prerequisites, and each course is independent.
**Example 3:**
**Input:** numCourses = 3, prerequisites = \[\[1,2\],\[1,0\],\[2,0\]\], queries = \[\[1,0\],\[1,2\]\]
**Output:** \[true,true\]
**Constraints:**
* `2 <= numCourses <= 100`
* `0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)`
* `prerequisites[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* All the pairs `[ai, bi]` are **unique**.
* The prerequisites graph has no cycles.
* `1 <= queries.length <= 104`
* `0 <= ui, vi <= n - 1`
* `ui != vi` | null |
python3 recursion + memoization | course-schedule-iv | 0 | 1 | \n\n# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n\n @cache\n def check(n,target):\n nonlocal d\n if n == target:\n return True\n \n for e in d[n]:\n if check(e,target):\n return True\n\n return False\n\n\n res = []\n d = defaultdict(list)\n for x,y in prerequisites:\n d[x].append(y)\n for x,y in queries:\n res.append(check(x,y))\n \n return res\n``` | 1 | You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function:
You want to use the modify function to covert `arr` to `nums` using the minimum number of calls.
Return _the minimum number of function calls to make_ `nums` _from_ `arr`.
The test cases are generated so that the answer fits in a **32-bit** signed integer.
**Example 1:**
**Input:** nums = \[1,5\]
**Output:** 5
**Explanation:** Increment by 1 (second element): \[0, 0\] to get \[0, 1\] (1 operation).
Double all the elements: \[0, 1\] -> \[0, 2\] -> \[0, 4\] (2 operations).
Increment by 1 (both elements) \[0, 4\] -> \[1, 4\] -> **\[1, 5\]** (2 operations).
Total of operations: 1 + 2 + 2 = 5.
**Example 2:**
**Input:** nums = \[2,2\]
**Output:** 3
**Explanation:** Increment by 1 (both elements) \[0, 0\] -> \[0, 1\] -> \[1, 1\] (2 operations).
Double all the elements: \[1, 1\] -> **\[2, 2\]** (1 operation).
Total of operations: 2 + 1 = 3.
**Example 3:**
**Input:** nums = \[4,2,5\]
**Output:** 6
**Explanation:** (initial)\[0,0,0\] -> \[1,0,0\] -> \[1,0,1\] -> \[2,0,2\] -> \[2,1,2\] -> \[4,2,4\] -> **\[4,2,5\]**(nums).
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109` | Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array. |
[python3][Topological Sort][BFS] Clear solution with comments | course-schedule-iv | 0 | 1 | Summary: the idea is to use topological sort to create a prerequisite lookup dictionary. \n\nSince this method is query-intensive, so we need to have O(1) time for query. In this case, we need to create a dictionary with each course as the key and the value is a set including all the prerequisites of this course. This lookup dictionary can be created by doing topological sort. \n\n```\nfrom collections import defaultdict, deque\n\nclass Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n neighbors = {node: set() for node in range(numCourses)} # store the graph\n indegree = defaultdict(int) # store indegree info for each node\n pre_lookup = defaultdict(set) # store the prerequisites info for each node\n \n # create the graph\n for pre, post in prerequisites:\n neighbors[pre].add(post)\n indegree[post] += 1\n \n # add 0 degree nodes into queue for topological sort\n queue = deque([])\n for n in neighbors:\n if indegree[n] == 0:\n queue.append(n)\n \n # use BFS to do topological sort to create a prerequisite lookup dictionary\n while queue:\n cur = queue.popleft()\n for neighbor in neighbors[cur]:\n pre_lookup[neighbor].add(cur) # add current node as the prerequisite of this neighbor node\n pre_lookup[neighbor].update(pre_lookup[cur]) # add all the preqs for current node to the neighbor node\'s preqs\n \n indegree[neighbor] -= 1 # regular topological search operations\n if indegree[neighbor] == 0:\n queue.append(neighbor)\n \n # traverse the queries and return the results\n result = [True if q[0] in pre_lookup[q[1]] else False for q in queries]\n \n return result\n```\n\n | 13 | There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take course `bi`.
* For example, the pair `[0, 1]` indicates that you have to take course `0` before you can take course `1`.
Prerequisites can also be **indirect**. If course `a` is a prerequisite of course `b`, and course `b` is a prerequisite of course `c`, then course `a` is a prerequisite of course `c`.
You are also given an array `queries` where `queries[j] = [uj, vj]`. For the `jth` query, you should answer whether course `uj` is a prerequisite of course `vj` or not.
Return _a boolean array_ `answer`_, where_ `answer[j]` _is the answer to the_ `jth` _query._
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\], queries = \[\[0,1\],\[1,0\]\]
**Output:** \[false,true\]
**Explanation:** The pair \[1, 0\] indicates that you have to take course 1 before you can take course 0.
Course 0 is not a prerequisite of course 1, but the opposite is true.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\], queries = \[\[1,0\],\[0,1\]\]
**Output:** \[false,false\]
**Explanation:** There are no prerequisites, and each course is independent.
**Example 3:**
**Input:** numCourses = 3, prerequisites = \[\[1,2\],\[1,0\],\[2,0\]\], queries = \[\[1,0\],\[1,2\]\]
**Output:** \[true,true\]
**Constraints:**
* `2 <= numCourses <= 100`
* `0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)`
* `prerequisites[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* All the pairs `[ai, bi]` are **unique**.
* The prerequisites graph has no cycles.
* `1 <= queries.length <= 104`
* `0 <= ui, vi <= n - 1`
* `ui != vi` | null |
[python3][Topological Sort][BFS] Clear solution with comments | course-schedule-iv | 0 | 1 | Summary: the idea is to use topological sort to create a prerequisite lookup dictionary. \n\nSince this method is query-intensive, so we need to have O(1) time for query. In this case, we need to create a dictionary with each course as the key and the value is a set including all the prerequisites of this course. This lookup dictionary can be created by doing topological sort. \n\n```\nfrom collections import defaultdict, deque\n\nclass Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n neighbors = {node: set() for node in range(numCourses)} # store the graph\n indegree = defaultdict(int) # store indegree info for each node\n pre_lookup = defaultdict(set) # store the prerequisites info for each node\n \n # create the graph\n for pre, post in prerequisites:\n neighbors[pre].add(post)\n indegree[post] += 1\n \n # add 0 degree nodes into queue for topological sort\n queue = deque([])\n for n in neighbors:\n if indegree[n] == 0:\n queue.append(n)\n \n # use BFS to do topological sort to create a prerequisite lookup dictionary\n while queue:\n cur = queue.popleft()\n for neighbor in neighbors[cur]:\n pre_lookup[neighbor].add(cur) # add current node as the prerequisite of this neighbor node\n pre_lookup[neighbor].update(pre_lookup[cur]) # add all the preqs for current node to the neighbor node\'s preqs\n \n indegree[neighbor] -= 1 # regular topological search operations\n if indegree[neighbor] == 0:\n queue.append(neighbor)\n \n # traverse the queries and return the results\n result = [True if q[0] in pre_lookup[q[1]] else False for q in queries]\n \n return result\n```\n\n | 13 | You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function:
You want to use the modify function to covert `arr` to `nums` using the minimum number of calls.
Return _the minimum number of function calls to make_ `nums` _from_ `arr`.
The test cases are generated so that the answer fits in a **32-bit** signed integer.
**Example 1:**
**Input:** nums = \[1,5\]
**Output:** 5
**Explanation:** Increment by 1 (second element): \[0, 0\] to get \[0, 1\] (1 operation).
Double all the elements: \[0, 1\] -> \[0, 2\] -> \[0, 4\] (2 operations).
Increment by 1 (both elements) \[0, 4\] -> \[1, 4\] -> **\[1, 5\]** (2 operations).
Total of operations: 1 + 2 + 2 = 5.
**Example 2:**
**Input:** nums = \[2,2\]
**Output:** 3
**Explanation:** Increment by 1 (both elements) \[0, 0\] -> \[0, 1\] -> \[1, 1\] (2 operations).
Double all the elements: \[1, 1\] -> **\[2, 2\]** (1 operation).
Total of operations: 2 + 1 = 3.
**Example 3:**
**Input:** nums = \[4,2,5\]
**Output:** 6
**Explanation:** (initial)\[0,0,0\] -> \[1,0,0\] -> \[1,0,1\] -> \[2,0,2\] -> \[2,1,2\] -> \[4,2,4\] -> **\[4,2,5\]**(nums).
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109` | Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array. |
( ͡° ͜ʖ ͡°)👉|| Beats 97.99%|| JAVA|| PYTHON||EASY SOLUTION💯☑️ | course-schedule-iv | 1 | 1 | # If you find it useful, please upvote so that others can find it easily.\n# Code\n```Java []\nclass Solution {\n public void fillGraph(boolean[][] graph, int i, boolean[] visited){\n if (visited[i])\n return;\n visited[i] = true;\n for (int j=0;j<graph[i].length;j++){\n if (graph[i][j]){\n fillGraph(graph, j, visited);\n for (int k=0;k<graph[j].length;k++){\n if (graph[j][k])\n graph[i][k] = true;\n }\n }\n }\n }\n \n public List<Boolean> checkIfPrerequisite(int n, int[][] prerequisites, int[][] queries) {\n boolean[][] graph = new boolean[n][n];\n \n for (int i=0;i<n;i++)\n graph[i][i] = true;\n\n for (int[] entry: prerequisites)\n graph[entry[0]][entry[1]] = true;\n \n boolean[] visited = new boolean[n];\n for (int i=0;i<n;i++)\n fillGraph(graph, i, visited);\n \n List<Boolean> responses = new ArrayList<Boolean>();\n for (int[] query: queries)\n responses.add(graph[query[0]][query[1]]);\n return responses;\n }\n}\n```\n```python []\nclass Solution(object):\n def checkIfPrerequisite(self, numCourses, prerequisites, queries):\n adj={i:[] for i in range(numCourses)}\n\n for x,y in prerequisites:\n adj[y].append(x)\n res=[]\n def dfs(crs):\n if crs not in premap:\n premap[crs]=set()\n for nei in adj[crs]:\n premap[crs]|=dfs(nei)\n premap[crs].add(crs)\n return premap[crs]\n\n premap={}\n for i in range(numCourses):\n dfs(i) \n for x,y in queries:\n res.append(x in premap[y])\n return res \n \n```\n\n | 2 | There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take course `bi`.
* For example, the pair `[0, 1]` indicates that you have to take course `0` before you can take course `1`.
Prerequisites can also be **indirect**. If course `a` is a prerequisite of course `b`, and course `b` is a prerequisite of course `c`, then course `a` is a prerequisite of course `c`.
You are also given an array `queries` where `queries[j] = [uj, vj]`. For the `jth` query, you should answer whether course `uj` is a prerequisite of course `vj` or not.
Return _a boolean array_ `answer`_, where_ `answer[j]` _is the answer to the_ `jth` _query._
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\], queries = \[\[0,1\],\[1,0\]\]
**Output:** \[false,true\]
**Explanation:** The pair \[1, 0\] indicates that you have to take course 1 before you can take course 0.
Course 0 is not a prerequisite of course 1, but the opposite is true.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\], queries = \[\[1,0\],\[0,1\]\]
**Output:** \[false,false\]
**Explanation:** There are no prerequisites, and each course is independent.
**Example 3:**
**Input:** numCourses = 3, prerequisites = \[\[1,2\],\[1,0\],\[2,0\]\], queries = \[\[1,0\],\[1,2\]\]
**Output:** \[true,true\]
**Constraints:**
* `2 <= numCourses <= 100`
* `0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)`
* `prerequisites[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* All the pairs `[ai, bi]` are **unique**.
* The prerequisites graph has no cycles.
* `1 <= queries.length <= 104`
* `0 <= ui, vi <= n - 1`
* `ui != vi` | null |
( ͡° ͜ʖ ͡°)👉|| Beats 97.99%|| JAVA|| PYTHON||EASY SOLUTION💯☑️ | course-schedule-iv | 1 | 1 | # If you find it useful, please upvote so that others can find it easily.\n# Code\n```Java []\nclass Solution {\n public void fillGraph(boolean[][] graph, int i, boolean[] visited){\n if (visited[i])\n return;\n visited[i] = true;\n for (int j=0;j<graph[i].length;j++){\n if (graph[i][j]){\n fillGraph(graph, j, visited);\n for (int k=0;k<graph[j].length;k++){\n if (graph[j][k])\n graph[i][k] = true;\n }\n }\n }\n }\n \n public List<Boolean> checkIfPrerequisite(int n, int[][] prerequisites, int[][] queries) {\n boolean[][] graph = new boolean[n][n];\n \n for (int i=0;i<n;i++)\n graph[i][i] = true;\n\n for (int[] entry: prerequisites)\n graph[entry[0]][entry[1]] = true;\n \n boolean[] visited = new boolean[n];\n for (int i=0;i<n;i++)\n fillGraph(graph, i, visited);\n \n List<Boolean> responses = new ArrayList<Boolean>();\n for (int[] query: queries)\n responses.add(graph[query[0]][query[1]]);\n return responses;\n }\n}\n```\n```python []\nclass Solution(object):\n def checkIfPrerequisite(self, numCourses, prerequisites, queries):\n adj={i:[] for i in range(numCourses)}\n\n for x,y in prerequisites:\n adj[y].append(x)\n res=[]\n def dfs(crs):\n if crs not in premap:\n premap[crs]=set()\n for nei in adj[crs]:\n premap[crs]|=dfs(nei)\n premap[crs].add(crs)\n return premap[crs]\n\n premap={}\n for i in range(numCourses):\n dfs(i) \n for x,y in queries:\n res.append(x in premap[y])\n return res \n \n```\n\n | 2 | You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function:
You want to use the modify function to covert `arr` to `nums` using the minimum number of calls.
Return _the minimum number of function calls to make_ `nums` _from_ `arr`.
The test cases are generated so that the answer fits in a **32-bit** signed integer.
**Example 1:**
**Input:** nums = \[1,5\]
**Output:** 5
**Explanation:** Increment by 1 (second element): \[0, 0\] to get \[0, 1\] (1 operation).
Double all the elements: \[0, 1\] -> \[0, 2\] -> \[0, 4\] (2 operations).
Increment by 1 (both elements) \[0, 4\] -> \[1, 4\] -> **\[1, 5\]** (2 operations).
Total of operations: 1 + 2 + 2 = 5.
**Example 2:**
**Input:** nums = \[2,2\]
**Output:** 3
**Explanation:** Increment by 1 (both elements) \[0, 0\] -> \[0, 1\] -> \[1, 1\] (2 operations).
Double all the elements: \[1, 1\] -> **\[2, 2\]** (1 operation).
Total of operations: 2 + 1 = 3.
**Example 3:**
**Input:** nums = \[4,2,5\]
**Output:** 6
**Explanation:** (initial)\[0,0,0\] -> \[1,0,0\] -> \[1,0,1\] -> \[2,0,2\] -> \[2,1,2\] -> \[4,2,4\] -> **\[4,2,5\]**(nums).
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109` | Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array. |
Simple Solution DFS ( finding Indirectly connected edges ) , in Python | course-schedule-iv | 0 | 1 | # Code\n```\nclass Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n\n graph = {}\n for i in range(numCourses): graph[i] = []\n\n for u , v in prerequisites: \n graph[u] += [v]\n\n d = {} # to maintain all INDIRECT NODES also ..!!!\n for i in range(numCourses): d[i] = set()\n\n visit = [0]*numCourses\n\n\n\n # DFS ...!!!!\n def dfs( node ):\n visit[node] = 1\n\n for ele in graph[node]:\n # need to add that element too.!!!!\n d[node].add(ele)\n\n if visit[ele] == 0: # if ele not already registered ..!!! then visit\n dfs(ele)\n \n for i in d[ele]: # add all nodes from that element ot the d[node]\n d[node].add(i)\n\n return d[node]\n\n\n\n for i in range(numCourses):\n if visit[i] == 0:\n dfs(i)\n\n ans = []\n for q in queries:\n if q[1] in d[q[0]]: # if there is a indirect Prerequisites \n ans += [True]\n else:\n ans += [False]\n return ans\n\n \n``` | 1 | There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take course `bi`.
* For example, the pair `[0, 1]` indicates that you have to take course `0` before you can take course `1`.
Prerequisites can also be **indirect**. If course `a` is a prerequisite of course `b`, and course `b` is a prerequisite of course `c`, then course `a` is a prerequisite of course `c`.
You are also given an array `queries` where `queries[j] = [uj, vj]`. For the `jth` query, you should answer whether course `uj` is a prerequisite of course `vj` or not.
Return _a boolean array_ `answer`_, where_ `answer[j]` _is the answer to the_ `jth` _query._
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\], queries = \[\[0,1\],\[1,0\]\]
**Output:** \[false,true\]
**Explanation:** The pair \[1, 0\] indicates that you have to take course 1 before you can take course 0.
Course 0 is not a prerequisite of course 1, but the opposite is true.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\], queries = \[\[1,0\],\[0,1\]\]
**Output:** \[false,false\]
**Explanation:** There are no prerequisites, and each course is independent.
**Example 3:**
**Input:** numCourses = 3, prerequisites = \[\[1,2\],\[1,0\],\[2,0\]\], queries = \[\[1,0\],\[1,2\]\]
**Output:** \[true,true\]
**Constraints:**
* `2 <= numCourses <= 100`
* `0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)`
* `prerequisites[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* All the pairs `[ai, bi]` are **unique**.
* The prerequisites graph has no cycles.
* `1 <= queries.length <= 104`
* `0 <= ui, vi <= n - 1`
* `ui != vi` | null |
Simple Solution DFS ( finding Indirectly connected edges ) , in Python | course-schedule-iv | 0 | 1 | # Code\n```\nclass Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n\n graph = {}\n for i in range(numCourses): graph[i] = []\n\n for u , v in prerequisites: \n graph[u] += [v]\n\n d = {} # to maintain all INDIRECT NODES also ..!!!\n for i in range(numCourses): d[i] = set()\n\n visit = [0]*numCourses\n\n\n\n # DFS ...!!!!\n def dfs( node ):\n visit[node] = 1\n\n for ele in graph[node]:\n # need to add that element too.!!!!\n d[node].add(ele)\n\n if visit[ele] == 0: # if ele not already registered ..!!! then visit\n dfs(ele)\n \n for i in d[ele]: # add all nodes from that element ot the d[node]\n d[node].add(i)\n\n return d[node]\n\n\n\n for i in range(numCourses):\n if visit[i] == 0:\n dfs(i)\n\n ans = []\n for q in queries:\n if q[1] in d[q[0]]: # if there is a indirect Prerequisites \n ans += [True]\n else:\n ans += [False]\n return ans\n\n \n``` | 1 | You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function:
You want to use the modify function to covert `arr` to `nums` using the minimum number of calls.
Return _the minimum number of function calls to make_ `nums` _from_ `arr`.
The test cases are generated so that the answer fits in a **32-bit** signed integer.
**Example 1:**
**Input:** nums = \[1,5\]
**Output:** 5
**Explanation:** Increment by 1 (second element): \[0, 0\] to get \[0, 1\] (1 operation).
Double all the elements: \[0, 1\] -> \[0, 2\] -> \[0, 4\] (2 operations).
Increment by 1 (both elements) \[0, 4\] -> \[1, 4\] -> **\[1, 5\]** (2 operations).
Total of operations: 1 + 2 + 2 = 5.
**Example 2:**
**Input:** nums = \[2,2\]
**Output:** 3
**Explanation:** Increment by 1 (both elements) \[0, 0\] -> \[0, 1\] -> \[1, 1\] (2 operations).
Double all the elements: \[1, 1\] -> **\[2, 2\]** (1 operation).
Total of operations: 2 + 1 = 3.
**Example 3:**
**Input:** nums = \[4,2,5\]
**Output:** 6
**Explanation:** (initial)\[0,0,0\] -> \[1,0,0\] -> \[1,0,1\] -> \[2,0,2\] -> \[2,1,2\] -> \[4,2,4\] -> **\[4,2,5\]**(nums).
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109` | Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array. |
[Python] DP + Reachability Test (Since its a DAG) | course-schedule-iv | 0 | 1 | ```\nclass Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n adjList = {}\n for i in range(numCourses):\n adjList[i] = []\n for i in prerequisites:\n adjList[i[0]].append(i[1])\n \n dp = {}\n def dfs(node, target):\n if node == target:\n return 1\n key = (node, target)\n if key in dp:\n return dp[key]\n y1 = 0\n for i in adjList[node]:\n y1 += dfs(i, target)\n dp[key] = y1\n return dp[key]\n res = []\n for i in queries:\n #dp = {}\n if dfs(i[0], i[1]) > 0:\n res.append(True)\n else:\n res.append(False)\n return res\n``` | 0 | There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take course `bi`.
* For example, the pair `[0, 1]` indicates that you have to take course `0` before you can take course `1`.
Prerequisites can also be **indirect**. If course `a` is a prerequisite of course `b`, and course `b` is a prerequisite of course `c`, then course `a` is a prerequisite of course `c`.
You are also given an array `queries` where `queries[j] = [uj, vj]`. For the `jth` query, you should answer whether course `uj` is a prerequisite of course `vj` or not.
Return _a boolean array_ `answer`_, where_ `answer[j]` _is the answer to the_ `jth` _query._
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\], queries = \[\[0,1\],\[1,0\]\]
**Output:** \[false,true\]
**Explanation:** The pair \[1, 0\] indicates that you have to take course 1 before you can take course 0.
Course 0 is not a prerequisite of course 1, but the opposite is true.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\], queries = \[\[1,0\],\[0,1\]\]
**Output:** \[false,false\]
**Explanation:** There are no prerequisites, and each course is independent.
**Example 3:**
**Input:** numCourses = 3, prerequisites = \[\[1,2\],\[1,0\],\[2,0\]\], queries = \[\[1,0\],\[1,2\]\]
**Output:** \[true,true\]
**Constraints:**
* `2 <= numCourses <= 100`
* `0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)`
* `prerequisites[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi`
* All the pairs `[ai, bi]` are **unique**.
* The prerequisites graph has no cycles.
* `1 <= queries.length <= 104`
* `0 <= ui, vi <= n - 1`
* `ui != vi` | null |
[Python] DP + Reachability Test (Since its a DAG) | course-schedule-iv | 0 | 1 | ```\nclass Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n adjList = {}\n for i in range(numCourses):\n adjList[i] = []\n for i in prerequisites:\n adjList[i[0]].append(i[1])\n \n dp = {}\n def dfs(node, target):\n if node == target:\n return 1\n key = (node, target)\n if key in dp:\n return dp[key]\n y1 = 0\n for i in adjList[node]:\n y1 += dfs(i, target)\n dp[key] = y1\n return dp[key]\n res = []\n for i in queries:\n #dp = {}\n if dfs(i[0], i[1]) > 0:\n res.append(True)\n else:\n res.append(False)\n return res\n``` | 0 | You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function:
You want to use the modify function to covert `arr` to `nums` using the minimum number of calls.
Return _the minimum number of function calls to make_ `nums` _from_ `arr`.
The test cases are generated so that the answer fits in a **32-bit** signed integer.
**Example 1:**
**Input:** nums = \[1,5\]
**Output:** 5
**Explanation:** Increment by 1 (second element): \[0, 0\] to get \[0, 1\] (1 operation).
Double all the elements: \[0, 1\] -> \[0, 2\] -> \[0, 4\] (2 operations).
Increment by 1 (both elements) \[0, 4\] -> \[1, 4\] -> **\[1, 5\]** (2 operations).
Total of operations: 1 + 2 + 2 = 5.
**Example 2:**
**Input:** nums = \[2,2\]
**Output:** 3
**Explanation:** Increment by 1 (both elements) \[0, 0\] -> \[0, 1\] -> \[1, 1\] (2 operations).
Double all the elements: \[1, 1\] -> **\[2, 2\]** (1 operation).
Total of operations: 2 + 1 = 3.
**Example 3:**
**Input:** nums = \[4,2,5\]
**Output:** 6
**Explanation:** (initial)\[0,0,0\] -> \[1,0,0\] -> \[1,0,1\] -> \[2,0,2\] -> \[2,1,2\] -> \[4,2,4\] -> **\[4,2,5\]**(nums).
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109` | Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array. |
Python 2 Solutions Very Easy to Understand | cherry-pickup-ii | 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. -->\nDynamic Programming\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```\nRecursion --> TLE\n\nclass Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n n,m = len(grid),len(grid[0])\n i = 0\n j1 = 0 # R1 position(0,0)\n j2 = m-1 # R2 position(0,m-1)\n\n def solve(i,j1,j2):\n # Base Condition\n\n if j1<0 or j1>=m or j2<0 or j2>=m:\n return float("-inf")\n if i == n-1:\n if j1 == j2:\n return grid[i][j1]\n else:\n return grid[i][j1] + grid[i][j2]\n\n # Choice Diagram\n\n maxi = 0\n dj = [-1,0,1]\n for dj1 in dj:\n for dj2 in dj:\n if j1 == j2:\n maxi = max((grid[i][j1] + solve(i+1,j1+dj1,j2+dj2)),maxi)\n else:\n maxi = max((grid[i][j1] + grid[i][j2] + solve(i+1,j1+dj1,j2+dj2)) , maxi)\n\n return maxi\n \n # Calling the main function\n \n return solve(i,j1,j2)\n```\n```\nTabulation\n\nclass Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n n,m = len(grid),len(grid[0])\n i = 0\n j1 = 0 # R1 position(0,0)\n j2 = m-1 # R2 position(0,m-1)\n # Creating a [n]*[[m]*[m]] matrix \n # In Python 3d - Matrix format --> [ [ [cols] rows ] depth ] \n t = [[[-1 for _ in range(m)] for _ in range(m)] for _ in range(n)]\n def solve(i,j1,j2):\n # Base Condition\n\n if j1<0 or j1>=m or j2<0 or j2>=m:\n return float("-inf")\n if i == n-1:\n if j1 == j2:\n return grid[i][j1]\n else:\n return grid[i][j1] + grid[i][j2]\n if t[i][j1][j2] != -1:\n return t[i][j1][j2]\n # Choice Diagram\n\n maxi = 0\n dj = [-1,0,1]\n for dj1 in dj:\n for dj2 in dj:\n if j1 == j2:\n maxi = max((grid[i][j1] + solve(i+1,j1+dj1,j2+dj2)),maxi)\n else:\n maxi = max((grid[i][j1] + grid[i][j2] + solve(i+1,j1+dj1,j2+dj2)) , maxi)\n t[i][j1][j2] = maxi\n return t[i][j1][j2]\n \n # Calling the main function\n \n return solve(i,j1,j2)\n``` | 1 | You are given a `rows x cols` matrix `grid` representing a field of cherries where `grid[i][j]` represents the number of cherries that you can collect from the `(i, j)` cell.
You have two robots that can collect cherries for you:
* **Robot #1** is located at the **top-left corner** `(0, 0)`, and
* **Robot #2** is located at the **top-right corner** `(0, cols - 1)`.
Return _the maximum number of cherries collection using both robots by following the rules below_:
* From a cell `(i, j)`, robots can move to cell `(i + 1, j - 1)`, `(i + 1, j)`, or `(i + 1, j + 1)`.
* When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.
* When both robots stay in the same cell, only one takes the cherries.
* Both robots cannot move outside of the grid at any moment.
* Both robots should reach the bottom row in `grid`.
**Example 1:**
**Input:** grid = \[\[3,1,1\],\[2,5,1\],\[1,5,5\],\[2,1,1\]\]
**Output:** 24
**Explanation:** Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
Total of cherries: 12 + 12 = 24.
**Example 2:**
**Input:** grid = \[\[1,0,0,0,0,0,1\],\[2,0,0,0,0,3,0\],\[2,0,9,0,0,0,0\],\[0,3,0,5,4,0,0\],\[1,0,2,3,0,0,6\]\]
**Output:** 28
**Explanation:** Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.
Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.
Total of cherries: 17 + 11 = 28.
**Constraints:**
* `rows == grid.length`
* `cols == grid[i].length`
* `2 <= rows, cols <= 70`
* `0 <= grid[i][j] <= 100` | Sort the matrix row indexes by the number of soldiers and then row indexes. |
Python 2 Solutions Very Easy to Understand | cherry-pickup-ii | 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. -->\nDynamic Programming\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```\nRecursion --> TLE\n\nclass Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n n,m = len(grid),len(grid[0])\n i = 0\n j1 = 0 # R1 position(0,0)\n j2 = m-1 # R2 position(0,m-1)\n\n def solve(i,j1,j2):\n # Base Condition\n\n if j1<0 or j1>=m or j2<0 or j2>=m:\n return float("-inf")\n if i == n-1:\n if j1 == j2:\n return grid[i][j1]\n else:\n return grid[i][j1] + grid[i][j2]\n\n # Choice Diagram\n\n maxi = 0\n dj = [-1,0,1]\n for dj1 in dj:\n for dj2 in dj:\n if j1 == j2:\n maxi = max((grid[i][j1] + solve(i+1,j1+dj1,j2+dj2)),maxi)\n else:\n maxi = max((grid[i][j1] + grid[i][j2] + solve(i+1,j1+dj1,j2+dj2)) , maxi)\n\n return maxi\n \n # Calling the main function\n \n return solve(i,j1,j2)\n```\n```\nTabulation\n\nclass Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n n,m = len(grid),len(grid[0])\n i = 0\n j1 = 0 # R1 position(0,0)\n j2 = m-1 # R2 position(0,m-1)\n # Creating a [n]*[[m]*[m]] matrix \n # In Python 3d - Matrix format --> [ [ [cols] rows ] depth ] \n t = [[[-1 for _ in range(m)] for _ in range(m)] for _ in range(n)]\n def solve(i,j1,j2):\n # Base Condition\n\n if j1<0 or j1>=m or j2<0 or j2>=m:\n return float("-inf")\n if i == n-1:\n if j1 == j2:\n return grid[i][j1]\n else:\n return grid[i][j1] + grid[i][j2]\n if t[i][j1][j2] != -1:\n return t[i][j1][j2]\n # Choice Diagram\n\n maxi = 0\n dj = [-1,0,1]\n for dj1 in dj:\n for dj2 in dj:\n if j1 == j2:\n maxi = max((grid[i][j1] + solve(i+1,j1+dj1,j2+dj2)),maxi)\n else:\n maxi = max((grid[i][j1] + grid[i][j2] + solve(i+1,j1+dj1,j2+dj2)) , maxi)\n t[i][j1][j2] = maxi\n return t[i][j1][j2]\n \n # Calling the main function\n \n return solve(i,j1,j2)\n``` | 1 | Given a 2D array of characters `grid` of size `m x n`, you need to find if there exists any cycle consisting of the **same value** in `grid`.
A cycle is a path of **length 4 or more** in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the **same value** of the current cell.
Also, you cannot move to the cell that you visited in your last move. For example, the cycle `(1, 1) -> (1, 2) -> (1, 1)` is invalid because from `(1, 2)` we visited `(1, 1)` which was the last visited cell.
Return `true` if any cycle of the same value exists in `grid`, otherwise, return `false`.
**Example 1:**
**Input:** grid = \[\[ "a ", "a ", "a ", "a "\],\[ "a ", "b ", "b ", "a "\],\[ "a ", "b ", "b ", "a "\],\[ "a ", "a ", "a ", "a "\]\]
**Output:** true
**Explanation:** There are two valid cycles shown in different colors in the image below:
**Example 2:**
**Input:** grid = \[\[ "c ", "c ", "c ", "a "\],\[ "c ", "d ", "c ", "c "\],\[ "c ", "c ", "e ", "c "\],\[ "f ", "c ", "c ", "c "\]\]
**Output:** true
**Explanation:** There is only one valid cycle highlighted in the image below:
**Example 3:**
**Input:** grid = \[\[ "a ", "b ", "b "\],\[ "b ", "z ", "b "\],\[ "b ", "b ", "a "\]\]
**Output:** false
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 500`
* `grid` consists only of lowercase English letters. | Use dynammic programming, define DP[i][j][k]: The maximum cherries that both robots can take starting on the ith row, and column j and k of Robot 1 and 2 respectively. |
❤ [Python3] DYNAMIC PROGRAMMING (*´∇`)ノ, Explained | cherry-pickup-ii | 0 | 1 | We approach this problem using DP. For a table we define `dp[row][col_r1][col_r2]`: the maximum reward both robots can get starting at the row `row` and columns `col_r1` and `col_r2` for the first and second robot respectively. For example: `dp[1][3][7] = 11` means that both robots can pickup maximum 11 cherries if the first robot starts at the cell `(1;3)` and the second at the cell `(1;7)`. To fill this table we need to iterate grid upward since for the last row the maximum reward is known and equal to number of cherries on the cell. To calculate the next best move, we use a helper function `get_next_max`, which iterates over all possible next moves and chose the best one. If robots take same cell, the reward is divided by two.\n\nAs an optimisation, we use couple of tricks:\n* Notice that it\'s not necessarily to iterate over all columns since robots can not access all cells of the grid due to their movement limitation: <img src="https://assets.leetcode.com/users/images/61cc238a-305d-4540-8909-33ac17d595f9_1641608254.7267363.jpeg" width="400"> \nThat is why we got all those `max` and `min` in main for-loops: \n<img src="https://assets.leetcode.com/users/images/254232bb-6aef-4c46-9417-fd572bc206c3_1641609185.237019.jpeg" width="400">\n\n* We pad the `dp` with zeros on the left and right so it wouldn\'t be necessery to check whether we are out of bounds. That is explain why we always add 1 to column indecis: `dp[row][col_r1 + 1][col_r2 + 1]`.\n\n### Complexity:\nTime: **O(row * cols * cols)** - for the scan\nSpace: **O(row * cols * cols)** - for the table\n\nRuntime: **666 ms** \\m/...(>.<)\u2026\\m/, faster than **96.80%** of Python3 online submissions for Cherry Pickup II.\nMemory Usage: 17.9 MB, less than **82.61%** of Python3 online submissions for Cherry Pickup II.\n\n```\nclass Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n rows, cols = len(grid), len(grid[0])\n \n dp = [[[0]*(cols + 2) for _ in range(cols + 2)] for _ in range(rows + 1)]\n \n def get_next_max(row, col_r1, col_r2):\n res = 0\n for next_col_r1 in (col_r1 - 1, col_r1, col_r1 + 1):\n for next_col_r2 in (col_r2 - 1, col_r2, col_r2 + 1):\n res = max(res, dp[row + 1][next_col_r1 + 1][next_col_r2 + 1])\n\n return res\n \n for row in reversed(range(rows)):\n for col_r1 in range(min(cols, row + 2)):\n for col_r2 in range(max(0, cols - row - 1), cols):\n\n reward = grid[row][col_r1] + grid[row][col_r2]\n if col_r1 == col_r2:\n reward /= 2\n \n dp[row][col_r1 + 1][col_r2 + 1] = reward + get_next_max(row, col_r1, col_r2)\n \n return dp[0][1][cols]\n``` | 15 | You are given a `rows x cols` matrix `grid` representing a field of cherries where `grid[i][j]` represents the number of cherries that you can collect from the `(i, j)` cell.
You have two robots that can collect cherries for you:
* **Robot #1** is located at the **top-left corner** `(0, 0)`, and
* **Robot #2** is located at the **top-right corner** `(0, cols - 1)`.
Return _the maximum number of cherries collection using both robots by following the rules below_:
* From a cell `(i, j)`, robots can move to cell `(i + 1, j - 1)`, `(i + 1, j)`, or `(i + 1, j + 1)`.
* When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.
* When both robots stay in the same cell, only one takes the cherries.
* Both robots cannot move outside of the grid at any moment.
* Both robots should reach the bottom row in `grid`.
**Example 1:**
**Input:** grid = \[\[3,1,1\],\[2,5,1\],\[1,5,5\],\[2,1,1\]\]
**Output:** 24
**Explanation:** Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.
Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.
Total of cherries: 12 + 12 = 24.
**Example 2:**
**Input:** grid = \[\[1,0,0,0,0,0,1\],\[2,0,0,0,0,3,0\],\[2,0,9,0,0,0,0\],\[0,3,0,5,4,0,0\],\[1,0,2,3,0,0,6\]\]
**Output:** 28
**Explanation:** Path of robot #1 and #2 are described in color green and blue respectively.
Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.
Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.
Total of cherries: 17 + 11 = 28.
**Constraints:**
* `rows == grid.length`
* `cols == grid[i].length`
* `2 <= rows, cols <= 70`
* `0 <= grid[i][j] <= 100` | Sort the matrix row indexes by the number of soldiers and then row indexes. |
❤ [Python3] DYNAMIC PROGRAMMING (*´∇`)ノ, Explained | cherry-pickup-ii | 0 | 1 | We approach this problem using DP. For a table we define `dp[row][col_r1][col_r2]`: the maximum reward both robots can get starting at the row `row` and columns `col_r1` and `col_r2` for the first and second robot respectively. For example: `dp[1][3][7] = 11` means that both robots can pickup maximum 11 cherries if the first robot starts at the cell `(1;3)` and the second at the cell `(1;7)`. To fill this table we need to iterate grid upward since for the last row the maximum reward is known and equal to number of cherries on the cell. To calculate the next best move, we use a helper function `get_next_max`, which iterates over all possible next moves and chose the best one. If robots take same cell, the reward is divided by two.\n\nAs an optimisation, we use couple of tricks:\n* Notice that it\'s not necessarily to iterate over all columns since robots can not access all cells of the grid due to their movement limitation: <img src="https://assets.leetcode.com/users/images/61cc238a-305d-4540-8909-33ac17d595f9_1641608254.7267363.jpeg" width="400"> \nThat is why we got all those `max` and `min` in main for-loops: \n<img src="https://assets.leetcode.com/users/images/254232bb-6aef-4c46-9417-fd572bc206c3_1641609185.237019.jpeg" width="400">\n\n* We pad the `dp` with zeros on the left and right so it wouldn\'t be necessery to check whether we are out of bounds. That is explain why we always add 1 to column indecis: `dp[row][col_r1 + 1][col_r2 + 1]`.\n\n### Complexity:\nTime: **O(row * cols * cols)** - for the scan\nSpace: **O(row * cols * cols)** - for the table\n\nRuntime: **666 ms** \\m/...(>.<)\u2026\\m/, faster than **96.80%** of Python3 online submissions for Cherry Pickup II.\nMemory Usage: 17.9 MB, less than **82.61%** of Python3 online submissions for Cherry Pickup II.\n\n```\nclass Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n rows, cols = len(grid), len(grid[0])\n \n dp = [[[0]*(cols + 2) for _ in range(cols + 2)] for _ in range(rows + 1)]\n \n def get_next_max(row, col_r1, col_r2):\n res = 0\n for next_col_r1 in (col_r1 - 1, col_r1, col_r1 + 1):\n for next_col_r2 in (col_r2 - 1, col_r2, col_r2 + 1):\n res = max(res, dp[row + 1][next_col_r1 + 1][next_col_r2 + 1])\n\n return res\n \n for row in reversed(range(rows)):\n for col_r1 in range(min(cols, row + 2)):\n for col_r2 in range(max(0, cols - row - 1), cols):\n\n reward = grid[row][col_r1] + grid[row][col_r2]\n if col_r1 == col_r2:\n reward /= 2\n \n dp[row][col_r1 + 1][col_r2 + 1] = reward + get_next_max(row, col_r1, col_r2)\n \n return dp[0][1][cols]\n``` | 15 | Given a 2D array of characters `grid` of size `m x n`, you need to find if there exists any cycle consisting of the **same value** in `grid`.
A cycle is a path of **length 4 or more** in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the **same value** of the current cell.
Also, you cannot move to the cell that you visited in your last move. For example, the cycle `(1, 1) -> (1, 2) -> (1, 1)` is invalid because from `(1, 2)` we visited `(1, 1)` which was the last visited cell.
Return `true` if any cycle of the same value exists in `grid`, otherwise, return `false`.
**Example 1:**
**Input:** grid = \[\[ "a ", "a ", "a ", "a "\],\[ "a ", "b ", "b ", "a "\],\[ "a ", "b ", "b ", "a "\],\[ "a ", "a ", "a ", "a "\]\]
**Output:** true
**Explanation:** There are two valid cycles shown in different colors in the image below:
**Example 2:**
**Input:** grid = \[\[ "c ", "c ", "c ", "a "\],\[ "c ", "d ", "c ", "c "\],\[ "c ", "c ", "e ", "c "\],\[ "f ", "c ", "c ", "c "\]\]
**Output:** true
**Explanation:** There is only one valid cycle highlighted in the image below:
**Example 3:**
**Input:** grid = \[\[ "a ", "b ", "b "\],\[ "b ", "z ", "b "\],\[ "b ", "b ", "a "\]\]
**Output:** false
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 500`
* `grid` consists only of lowercase English letters. | Use dynammic programming, define DP[i][j][k]: The maximum cherries that both robots can take starting on the ith row, and column j and k of Robot 1 and 2 respectively. |
【Video】Give me 5 minutes - 2 solutions - How we think about a solution | maximum-product-of-two-elements-in-an-array | 1 | 1 | # Intuition\nKeep the largest number so far\n\n---\n\n# Solution Video\n\nhttps://youtu.be/JV5Kuinx-m0\n\n\u25A0 Timeline of the video\n\n`0:05` Explain algorithm of Solution 1\n`3:18` Coding of solution 1\n`4:18` Time Complexity and Space Complexity of solution 1\n`4:29` Step by step algorithm of solution 1\n`4:36` Explain key points of Solution 2\n`5:25` Coding of Solution 2\n`6:50` Time Complexity and Space Complexity of Solution 2\n`7:03` Step by step algorithm with my stack solution code\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 3,424\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n---\n\n# Approach\n\n## How we think about a solution\n\nSeems like all numbers are positive, so simply all we have to do is to find the two largest numbers in input array.\n\nThe key point of my first solution is\n\n---\n\n\u2B50\uFE0F Points\n\nKeep the largest number(= `cur_max` in the solution code) so far and compare \n\n```\nres vs (cur_max - 1) * (nums[i] - 1)\n```\n\n`res` is current max result so far\n`nums[i]` is current number\n\n---\n\nLet\'s see one by one.\n\n```\nInput: nums = [1,5,4,5]\n```\nWe keep the number at index 0 as a current max number.\n```\nres = 0\ncur_max = 1 (= nums[0])\n```\nStart iteration from index 1. \n```\nAt index 1, Compare\n\nmax(res, (cur_max - 1) * (nums[i] - 1))\n\u2192 max(0, (1 - 1) * (5 - 1))\n= 0\n\nres = 0\n```\n`res` is still `0` and we need to update `cur_max` if current number is greater than `cur_max`.\n```\ncur_max = max(cur_max, nums[i])\n= 1 vs 5\n\ncur_max = 5\n``` \nI\'ll speed up.\n```\nAt index 2, Compare\n\nmax(res, (cur_max - 1) * (nums[i] - 1))\n\u2192 max(0, (5 - 1) * (4 - 1))\n= 12\n\nres = 12\ncur_max = 5 (= max(5, 4))\n```\n\n```\nAt index 3, Compare\n\nmax(res, (cur_max - 1) * (nums[i] - 1))\n\u2192 max(12, (5 - 1) * (5 - 1))\n= 16\n\nres = 16\ncur_max = 5 (= max(5, 5))\n```\n```\nOutput: 16\n```\n\nEasy \uD83D\uDE06!\nLet\'s see a real algorithm!\n\n\n---\n\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```python []\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n res = 0\n cur_max = nums[0]\n\n for i in range(1, len(nums)):\n res = max(res, (cur_max - 1) * (nums[i] - 1))\n cur_max = max(cur_max, nums[i])\n\n return res \n```\n```javascript []\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maxProduct = function(nums) {\n let res = 0;\n let curMax = nums[0];\n\n for (let i = 1; i < nums.length; i++) {\n res = Math.max(res, (curMax - 1) * (nums[i] - 1));\n curMax = Math.max(curMax, nums[i]);\n }\n\n return res; \n};\n```\n```java []\nclass Solution {\n public int maxProduct(int[] nums) {\n int res = 0;\n int curMax = nums[0];\n\n for (int i = 1; i < nums.length; i++) {\n res = Math.max(res, (curMax - 1) * (nums[i] - 1));\n curMax = Math.max(curMax, nums[i]);\n }\n\n return res; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int maxProduct(vector<int>& nums) {\n int res = 0;\n int curMax = nums[0];\n\n for (int i = 1; i < nums.size(); i++) {\n res = max(res, (curMax - 1) * (nums[i] - 1));\n curMax = max(curMax, nums[i]);\n }\n\n return res; \n }\n};\n```\n\n## Step by step algorithm\n\n**Initialization:**\n```python\nres = 0\ncur_max = nums[0]\n```\nIn this section, `res` is initialized to 0, and `cur_max` is initialized to the first element of the `nums` list. These variables will be used to keep track of the maximum product and the maximum value encountered during the iterations, respectively.\n\n**Iteration through the List:**\n```python\nfor i in range(1, len(nums)):\n res = max(res, (cur_max - 1) * (nums[i] - 1))\n cur_max = max(cur_max, nums[i])\n```\nIn this section, the code iterates through the list starting from the second element (index 1). For each element at index `i`:\n- `res` is updated to the maximum of its current value and the product of `(cur_max - 1) * (nums[i] - 1)`. This ensures that `res` always holds the maximum product found so far.\n- `cur_max` is updated to the maximum of its current value and the current element `nums[i]`. This ensures that `cur_max` always holds the maximum value encountered in the list up to the current index.\n\n**Return Result:**\n```python\nreturn res\n```\nAfter the loop completes, the final value of `res` represents the maximum product of two distinct elements in the list. The function returns this maximum product.\n\n\n---\n\n# Solution 2\n\nBasically, we try to find the first max and second max numbers.\n\n---\n\n\u2B50\uFE0F Points\n\nIf current number is greater than the first max number so far, then \n\n```\ncurrent number will be the first max number\ncurrent first max number will be second max number\n```\nIf current number is less than the first max number so far, then compare \n```\nsecond max number = max(second max number, current number)\n```\n\nBecause there is still possibility that current number will be the second max number.\n\n---\n\nAt last, we multiply the first and second max numbers.\n\nEasy!\uD83D\uDE04\nLet\'s see a real algorithm\n\n\n---\n\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```python []\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n first_max, second_max = 0, 0\n for num in nums:\n if num > first_max:\n second_max, first_max = first_max, num\n else:\n second_max = max(second_max, num)\n\n return (first_max - 1) * (second_max - 1)\n```\n```javascript []\nvar maxProduct = function(nums) {\n let firstMax = 0;\n let secondMax = 0;\n\n for (let num of nums) {\n if (num > firstMax) {\n [secondMax, firstMax] = [firstMax, num];\n } else {\n secondMax = Math.max(secondMax, num);\n }\n }\n\n return (firstMax - 1) * (secondMax - 1); \n};\n```\n```java []\nclass Solution {\n public int maxProduct(int[] nums) {\n int firstMax = 0;\n int secondMax = 0;\n\n for (int num : nums) {\n if (num > firstMax) {\n secondMax = firstMax;\n firstMax = num;\n } else {\n secondMax = Math.max(secondMax, num);\n }\n }\n\n return (firstMax - 1) * (secondMax - 1); \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int maxProduct(vector<int>& nums) {\n int firstMax = 0;\n int secondMax = 0;\n\n for (int num : nums) {\n if (num > firstMax) {\n swap(secondMax, firstMax);\n firstMax = num;\n } else {\n secondMax = max(secondMax, num);\n }\n }\n\n return (firstMax - 1) * (secondMax - 1); \n }\n};\n```\n\n## Step by step algorithm\n\n1. **Initialization:**\n\n```\nfirst_max, second_max = 0, 0\n```\n - `first_max` and `second_max` are initialized to 0. These variables will be used to keep track of the two largest elements in the list.\n\n2. **Iteration through the List:**\n\n```\nfor num in nums:\n if num > first_max:\n second_max, first_max = first_max, num\n else:\n second_max = max(second_max, num)\n```\n\n - The code iterates through each element `num` in the `nums` list.\n - For each `num`:\n - If `num` is greater than `first_max`, it means `num` is the new maximum. Therefore, the values of `second_max` and `first_max` are updated accordingly. This is done using the simultaneous assignment technique in Python: `second_max, first_max = first_max, num`.\n - If `num` is not greater than `first_max` but is greater than `second_max`, it means `num` is the new second maximum. Therefore, `second_max` is updated using `second_max = max(second_max, num)`.\n\n3. **Return Result:**\n\n```\nreturn (first_max - 1) * (second_max - 1)\n```\n\n - After the loop completes, the function returns the product of `(first_max - 1)` and `(second_max - 1)`. This is because the task is to find the maximum product of two distinct elements, so we subtract 1 from each of the largest elements before multiplying.\n\nThe algorithm efficiently finds the two largest elements in the list and returns their product minus 1.\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n\u25A0 Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n\n### My next daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/special-positions-in-a-binary-matrix/solutions/4397604/video-give-me-5-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/qTAh4HGfUHk\n\n\u25A0 Timeline of the video\n\n`0:05` Explain algorithm of the first step\n`1:06` Explain algorithm of the second step\n`2:36` Coding\n`4:17` Time Complexity and Space Complexity\n`4:55` Step by step algorithm of my solution code\n\n### My previous daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/solutions/4388310/video-give-me-5-minutes-2-solutions-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/bTm-6y7Ob0A\n\n\u25A0 Timeline of the video\n\n`0:07` Explain algorithm of Solution 1\n`2:46` Coding of solution 1\n`3:49` Time Complexity and Space Complexity of solution 1\n`4:02` Step by step algorithm of solution 1\n`4:09` Explain key points of Solution 2\n`4:47` Explain the first key point\n`6:06` Explain the second key point\n`7:40` Explain the third key point\n`9:33` Coding of Solution 2\n`14:20` Time Complexity and Space Complexity of Solution 2\n`14:48` Step by step algorithm with my stack solution code\n\n | 27 | Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.
**Example 1:**
**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12.
**Example 2:**
**Input:** nums = \[1,5,4,5\]
**Output:** 16
**Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16.
**Example 3:**
**Input:** nums = \[3,7\]
**Output:** 12
**Constraints:**
* `2 <= nums.length <= 500`
* `1 <= nums[i] <= 10^3` | Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers. |
【Video】Give me 5 minutes - 2 solutions - How we think about a solution | maximum-product-of-two-elements-in-an-array | 1 | 1 | # Intuition\nKeep the largest number so far\n\n---\n\n# Solution Video\n\nhttps://youtu.be/JV5Kuinx-m0\n\n\u25A0 Timeline of the video\n\n`0:05` Explain algorithm of Solution 1\n`3:18` Coding of solution 1\n`4:18` Time Complexity and Space Complexity of solution 1\n`4:29` Step by step algorithm of solution 1\n`4:36` Explain key points of Solution 2\n`5:25` Coding of Solution 2\n`6:50` Time Complexity and Space Complexity of Solution 2\n`7:03` Step by step algorithm with my stack solution code\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 3,424\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n---\n\n# Approach\n\n## How we think about a solution\n\nSeems like all numbers are positive, so simply all we have to do is to find the two largest numbers in input array.\n\nThe key point of my first solution is\n\n---\n\n\u2B50\uFE0F Points\n\nKeep the largest number(= `cur_max` in the solution code) so far and compare \n\n```\nres vs (cur_max - 1) * (nums[i] - 1)\n```\n\n`res` is current max result so far\n`nums[i]` is current number\n\n---\n\nLet\'s see one by one.\n\n```\nInput: nums = [1,5,4,5]\n```\nWe keep the number at index 0 as a current max number.\n```\nres = 0\ncur_max = 1 (= nums[0])\n```\nStart iteration from index 1. \n```\nAt index 1, Compare\n\nmax(res, (cur_max - 1) * (nums[i] - 1))\n\u2192 max(0, (1 - 1) * (5 - 1))\n= 0\n\nres = 0\n```\n`res` is still `0` and we need to update `cur_max` if current number is greater than `cur_max`.\n```\ncur_max = max(cur_max, nums[i])\n= 1 vs 5\n\ncur_max = 5\n``` \nI\'ll speed up.\n```\nAt index 2, Compare\n\nmax(res, (cur_max - 1) * (nums[i] - 1))\n\u2192 max(0, (5 - 1) * (4 - 1))\n= 12\n\nres = 12\ncur_max = 5 (= max(5, 4))\n```\n\n```\nAt index 3, Compare\n\nmax(res, (cur_max - 1) * (nums[i] - 1))\n\u2192 max(12, (5 - 1) * (5 - 1))\n= 16\n\nres = 16\ncur_max = 5 (= max(5, 5))\n```\n```\nOutput: 16\n```\n\nEasy \uD83D\uDE06!\nLet\'s see a real algorithm!\n\n\n---\n\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```python []\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n res = 0\n cur_max = nums[0]\n\n for i in range(1, len(nums)):\n res = max(res, (cur_max - 1) * (nums[i] - 1))\n cur_max = max(cur_max, nums[i])\n\n return res \n```\n```javascript []\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maxProduct = function(nums) {\n let res = 0;\n let curMax = nums[0];\n\n for (let i = 1; i < nums.length; i++) {\n res = Math.max(res, (curMax - 1) * (nums[i] - 1));\n curMax = Math.max(curMax, nums[i]);\n }\n\n return res; \n};\n```\n```java []\nclass Solution {\n public int maxProduct(int[] nums) {\n int res = 0;\n int curMax = nums[0];\n\n for (int i = 1; i < nums.length; i++) {\n res = Math.max(res, (curMax - 1) * (nums[i] - 1));\n curMax = Math.max(curMax, nums[i]);\n }\n\n return res; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int maxProduct(vector<int>& nums) {\n int res = 0;\n int curMax = nums[0];\n\n for (int i = 1; i < nums.size(); i++) {\n res = max(res, (curMax - 1) * (nums[i] - 1));\n curMax = max(curMax, nums[i]);\n }\n\n return res; \n }\n};\n```\n\n## Step by step algorithm\n\n**Initialization:**\n```python\nres = 0\ncur_max = nums[0]\n```\nIn this section, `res` is initialized to 0, and `cur_max` is initialized to the first element of the `nums` list. These variables will be used to keep track of the maximum product and the maximum value encountered during the iterations, respectively.\n\n**Iteration through the List:**\n```python\nfor i in range(1, len(nums)):\n res = max(res, (cur_max - 1) * (nums[i] - 1))\n cur_max = max(cur_max, nums[i])\n```\nIn this section, the code iterates through the list starting from the second element (index 1). For each element at index `i`:\n- `res` is updated to the maximum of its current value and the product of `(cur_max - 1) * (nums[i] - 1)`. This ensures that `res` always holds the maximum product found so far.\n- `cur_max` is updated to the maximum of its current value and the current element `nums[i]`. This ensures that `cur_max` always holds the maximum value encountered in the list up to the current index.\n\n**Return Result:**\n```python\nreturn res\n```\nAfter the loop completes, the final value of `res` represents the maximum product of two distinct elements in the list. The function returns this maximum product.\n\n\n---\n\n# Solution 2\n\nBasically, we try to find the first max and second max numbers.\n\n---\n\n\u2B50\uFE0F Points\n\nIf current number is greater than the first max number so far, then \n\n```\ncurrent number will be the first max number\ncurrent first max number will be second max number\n```\nIf current number is less than the first max number so far, then compare \n```\nsecond max number = max(second max number, current number)\n```\n\nBecause there is still possibility that current number will be the second max number.\n\n---\n\nAt last, we multiply the first and second max numbers.\n\nEasy!\uD83D\uDE04\nLet\'s see a real algorithm\n\n\n---\n\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```python []\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n first_max, second_max = 0, 0\n for num in nums:\n if num > first_max:\n second_max, first_max = first_max, num\n else:\n second_max = max(second_max, num)\n\n return (first_max - 1) * (second_max - 1)\n```\n```javascript []\nvar maxProduct = function(nums) {\n let firstMax = 0;\n let secondMax = 0;\n\n for (let num of nums) {\n if (num > firstMax) {\n [secondMax, firstMax] = [firstMax, num];\n } else {\n secondMax = Math.max(secondMax, num);\n }\n }\n\n return (firstMax - 1) * (secondMax - 1); \n};\n```\n```java []\nclass Solution {\n public int maxProduct(int[] nums) {\n int firstMax = 0;\n int secondMax = 0;\n\n for (int num : nums) {\n if (num > firstMax) {\n secondMax = firstMax;\n firstMax = num;\n } else {\n secondMax = Math.max(secondMax, num);\n }\n }\n\n return (firstMax - 1) * (secondMax - 1); \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int maxProduct(vector<int>& nums) {\n int firstMax = 0;\n int secondMax = 0;\n\n for (int num : nums) {\n if (num > firstMax) {\n swap(secondMax, firstMax);\n firstMax = num;\n } else {\n secondMax = max(secondMax, num);\n }\n }\n\n return (firstMax - 1) * (secondMax - 1); \n }\n};\n```\n\n## Step by step algorithm\n\n1. **Initialization:**\n\n```\nfirst_max, second_max = 0, 0\n```\n - `first_max` and `second_max` are initialized to 0. These variables will be used to keep track of the two largest elements in the list.\n\n2. **Iteration through the List:**\n\n```\nfor num in nums:\n if num > first_max:\n second_max, first_max = first_max, num\n else:\n second_max = max(second_max, num)\n```\n\n - The code iterates through each element `num` in the `nums` list.\n - For each `num`:\n - If `num` is greater than `first_max`, it means `num` is the new maximum. Therefore, the values of `second_max` and `first_max` are updated accordingly. This is done using the simultaneous assignment technique in Python: `second_max, first_max = first_max, num`.\n - If `num` is not greater than `first_max` but is greater than `second_max`, it means `num` is the new second maximum. Therefore, `second_max` is updated using `second_max = max(second_max, num)`.\n\n3. **Return Result:**\n\n```\nreturn (first_max - 1) * (second_max - 1)\n```\n\n - After the loop completes, the function returns the product of `(first_max - 1)` and `(second_max - 1)`. This is because the task is to find the maximum product of two distinct elements, so we subtract 1 from each of the largest elements before multiplying.\n\nThe algorithm efficiently finds the two largest elements in the list and returns their product minus 1.\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n\u25A0 Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n\n### My next daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/special-positions-in-a-binary-matrix/solutions/4397604/video-give-me-5-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/qTAh4HGfUHk\n\n\u25A0 Timeline of the video\n\n`0:05` Explain algorithm of the first step\n`1:06` Explain algorithm of the second step\n`2:36` Coding\n`4:17` Time Complexity and Space Complexity\n`4:55` Step by step algorithm of my solution code\n\n### My previous daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/solutions/4388310/video-give-me-5-minutes-2-solutions-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/bTm-6y7Ob0A\n\n\u25A0 Timeline of the video\n\n`0:07` Explain algorithm of Solution 1\n`2:46` Coding of solution 1\n`3:49` Time Complexity and Space Complexity of solution 1\n`4:02` Step by step algorithm of solution 1\n`4:09` Explain key points of Solution 2\n`4:47` Explain the first key point\n`6:06` Explain the second key point\n`7:40` Explain the third key point\n`9:33` Coding of Solution 2\n`14:20` Time Complexity and Space Complexity of Solution 2\n`14:48` Step by step algorithm with my stack solution code\n\n | 27 | Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**.
Return _the length of the shortest subarray to remove_.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,2,3,10,4,2,3,5\]
**Output:** 3
**Explanation:** The shortest subarray we can remove is \[10,4,2\] of length 3. The remaining elements after that will be \[1,2,3,3,5\] which are sorted.
Another correct solution is to remove the subarray \[3,10,4\].
**Example 2:**
**Input:** arr = \[5,4,3,2,1\]
**Output:** 4
**Explanation:** Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either \[5,4,3,2\] or \[4,3,2,1\].
**Example 3:**
**Input:** arr = \[1,2,3\]
**Output:** 0
**Explanation:** The array is already non-decreasing. We do not need to remove any elements.
**Constraints:**
* `1 <= arr.length <= 105`
* `0 <= arr[i] <= 109` | Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1). |
✅✅|| EASY PEASY || C#, Java, Python || 🔥🔥🔥 | maximum-product-of-two-elements-in-an-array | 1 | 1 | # Intuition\nThe problem involves finding the maximum product of two elements in an array. The provided code suggests an approach of iteratively updating the two largest elements in the array as we traverse through it.\n\n# Approach\n1. Initialize two variables, `max1` and `max2`, to store the two largest elements in the array.\n2. Iterate through the array, updating `max1` and `max2` as needed.\n3. Calculate and return the product of `(max1 - 1) * (max2 - 1)`.\n\n# Complexity\n- **Time complexity:** O(n), where n is the length of the array. The algorithm makes a single pass through the array.\n- **Space complexity:** O(1), as the algorithm uses a constant amount of extra space to store `max1` and `max2`.\n\n```csharp []\npublic class Solution {\n public int MaxProduct(int[] nums) {\n int max1 = 0, max2 = 0;\n\n foreach (var num in nums) {\n if (num > max1) {\n max2 = max1;\n max1 = num;\n } else if (num > max2) {\n max2 = num;\n }\n }\n\n return (max1 - 1) * (max2 - 1);\n }\n}\n```\n```python []\nclass Solution:\n def maxProduct(self, nums):\n max1, max2 = 0, 0\n\n for num in nums:\n if num > max1:\n max2 = max1\n max1 = num\n elif num > max2:\n max2 = num\n\n return (max1 - 1) * (max2 - 1)\n\n```\n``` Java []\nimport java.util.Arrays;\n\npublic class Solution {\n public int maxProduct(int[] nums) {\n int max1 = 0, max2 = 0;\n\n for (int num : nums) {\n if (num > max1) {\n max2 = max1;\n max1 = num;\n } else if (num > max2) {\n max2 = num;\n }\n }\n\n return (max1 - 1) * (max2 - 1);\n }\n}\n```\n\n\n\n- Please upvote me !!! | 11 | Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.
**Example 1:**
**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12.
**Example 2:**
**Input:** nums = \[1,5,4,5\]
**Output:** 16
**Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16.
**Example 3:**
**Input:** nums = \[3,7\]
**Output:** 12
**Constraints:**
* `2 <= nums.length <= 500`
* `1 <= nums[i] <= 10^3` | Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers. |
✅✅|| EASY PEASY || C#, Java, Python || 🔥🔥🔥 | maximum-product-of-two-elements-in-an-array | 1 | 1 | # Intuition\nThe problem involves finding the maximum product of two elements in an array. The provided code suggests an approach of iteratively updating the two largest elements in the array as we traverse through it.\n\n# Approach\n1. Initialize two variables, `max1` and `max2`, to store the two largest elements in the array.\n2. Iterate through the array, updating `max1` and `max2` as needed.\n3. Calculate and return the product of `(max1 - 1) * (max2 - 1)`.\n\n# Complexity\n- **Time complexity:** O(n), where n is the length of the array. The algorithm makes a single pass through the array.\n- **Space complexity:** O(1), as the algorithm uses a constant amount of extra space to store `max1` and `max2`.\n\n```csharp []\npublic class Solution {\n public int MaxProduct(int[] nums) {\n int max1 = 0, max2 = 0;\n\n foreach (var num in nums) {\n if (num > max1) {\n max2 = max1;\n max1 = num;\n } else if (num > max2) {\n max2 = num;\n }\n }\n\n return (max1 - 1) * (max2 - 1);\n }\n}\n```\n```python []\nclass Solution:\n def maxProduct(self, nums):\n max1, max2 = 0, 0\n\n for num in nums:\n if num > max1:\n max2 = max1\n max1 = num\n elif num > max2:\n max2 = num\n\n return (max1 - 1) * (max2 - 1)\n\n```\n``` Java []\nimport java.util.Arrays;\n\npublic class Solution {\n public int maxProduct(int[] nums) {\n int max1 = 0, max2 = 0;\n\n for (int num : nums) {\n if (num > max1) {\n max2 = max1;\n max1 = num;\n } else if (num > max2) {\n max2 = num;\n }\n }\n\n return (max1 - 1) * (max2 - 1);\n }\n}\n```\n\n\n\n- Please upvote me !!! | 11 | Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**.
Return _the length of the shortest subarray to remove_.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,2,3,10,4,2,3,5\]
**Output:** 3
**Explanation:** The shortest subarray we can remove is \[10,4,2\] of length 3. The remaining elements after that will be \[1,2,3,3,5\] which are sorted.
Another correct solution is to remove the subarray \[3,10,4\].
**Example 2:**
**Input:** arr = \[5,4,3,2,1\]
**Output:** 4
**Explanation:** Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either \[5,4,3,2\] or \[4,3,2,1\].
**Example 3:**
**Input:** arr = \[1,2,3\]
**Output:** 0
**Explanation:** The array is already non-decreasing. We do not need to remove any elements.
**Constraints:**
* `1 <= arr.length <= 105`
* `0 <= arr[i] <= 109` | Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1). |
2 C++ 1 pass, priority_queue O(1) vs 3 Python 1-line codes|| 0ms beats 100% | maximum-product-of-two-elements-in-an-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIterate the `nums` to find the max & 2nd max.\n\n2nd O(1) C++ solution uses priority_queue of size at most 3 which is also fast & beats 100%.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nPython codes are provided with 1-line codes.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ vs $$O(n\\log n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code 0ms beats 100%\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n int maxProduct(vector<int>& nums) {\n int n=nums.size();\n if (n<3) return (nums[0]-1)*(nums.back()-1);\n int m0=nums[0],m1=nums[1];\n if(m0<m1) swap(m0,m1);\n for (int i=2;i<n;i++){\n int x=nums[i];\n if(x>m0){\n m1=m0, m0=x;\n }\n else if(x>m1) m1=x;\n }\n return (m0-1)*(m1-1);\n }\n};\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n# C++ using priority_queue|| 0ms beats 100%\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n int maxProduct(vector<int>& nums) {\n priority_queue<int, vector<int>, greater<int>> pq;\n for (int x: nums){\n pq.push(x);\n if (pq.size()>2) pq.pop(); \n }\n int product=pq.top()-1;\n pq.pop();\n product*=(pq.top()-1);\n return product;\n }\n};\n\n```\n# Python 1 line using sorted\n\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n return ((x:=sorted(nums))[-1]-1)*(x[-2]-1) \n```\n# Python 1 line 49ms beats 92.92%\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n return ((x:=sorted(nums)[-2:])[-1]-1)*(x[-2]-1) \n```\n# Python 1 line using heap.nlargest\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n return ((x:=heapq.nlargest(2, nums))[0]-1)*(x[1]-1)\n``` | 8 | Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.
**Example 1:**
**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12.
**Example 2:**
**Input:** nums = \[1,5,4,5\]
**Output:** 16
**Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16.
**Example 3:**
**Input:** nums = \[3,7\]
**Output:** 12
**Constraints:**
* `2 <= nums.length <= 500`
* `1 <= nums[i] <= 10^3` | Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers. |
2 C++ 1 pass, priority_queue O(1) vs 3 Python 1-line codes|| 0ms beats 100% | maximum-product-of-two-elements-in-an-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIterate the `nums` to find the max & 2nd max.\n\n2nd O(1) C++ solution uses priority_queue of size at most 3 which is also fast & beats 100%.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nPython codes are provided with 1-line codes.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ vs $$O(n\\log n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code 0ms beats 100%\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n int maxProduct(vector<int>& nums) {\n int n=nums.size();\n if (n<3) return (nums[0]-1)*(nums.back()-1);\n int m0=nums[0],m1=nums[1];\n if(m0<m1) swap(m0,m1);\n for (int i=2;i<n;i++){\n int x=nums[i];\n if(x>m0){\n m1=m0, m0=x;\n }\n else if(x>m1) m1=x;\n }\n return (m0-1)*(m1-1);\n }\n};\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n# C++ using priority_queue|| 0ms beats 100%\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n int maxProduct(vector<int>& nums) {\n priority_queue<int, vector<int>, greater<int>> pq;\n for (int x: nums){\n pq.push(x);\n if (pq.size()>2) pq.pop(); \n }\n int product=pq.top()-1;\n pq.pop();\n product*=(pq.top()-1);\n return product;\n }\n};\n\n```\n# Python 1 line using sorted\n\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n return ((x:=sorted(nums))[-1]-1)*(x[-2]-1) \n```\n# Python 1 line 49ms beats 92.92%\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n return ((x:=sorted(nums)[-2:])[-1]-1)*(x[-2]-1) \n```\n# Python 1 line using heap.nlargest\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n return ((x:=heapq.nlargest(2, nums))[0]-1)*(x[1]-1)\n``` | 8 | Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**.
Return _the length of the shortest subarray to remove_.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,2,3,10,4,2,3,5\]
**Output:** 3
**Explanation:** The shortest subarray we can remove is \[10,4,2\] of length 3. The remaining elements after that will be \[1,2,3,3,5\] which are sorted.
Another correct solution is to remove the subarray \[3,10,4\].
**Example 2:**
**Input:** arr = \[5,4,3,2,1\]
**Output:** 4
**Explanation:** Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either \[5,4,3,2\] or \[4,3,2,1\].
**Example 3:**
**Input:** arr = \[1,2,3\]
**Output:** 0
**Explanation:** The array is already non-decreasing. We do not need to remove any elements.
**Constraints:**
* `1 <= arr.length <= 105`
* `0 <= arr[i] <= 109` | Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1). |
✅☑[C++/Java/Python/JavaScript] || 3 Approaches || Beats 100% || EXPLAINED🔥 | maximum-product-of-two-elements-in-an-array | 1 | 1 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Brute Force)***\n1. The function iterates through the elements in the `nums` array using two nested loops (`i` and `j`) to consider all possible pairs of elements.\n1. For each pair of elements (`nums[i], nums[j]`), it calculates the product of `(nums[i] - 1) * (nums[j] - 1)`.\n1. It updates the `ans` variable to hold the maximum product found among all pairs considered.\n1. Finally, it returns the maximum product of two distinct elements in the array.\n\n# Complexity\n- *Time complexity:*\n $$O(n^2)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n // Function to find the maximum product of two distinct elements in the \'nums\' array\n int maxProduct(vector<int>& nums) {\n int ans = 0; // Initializing the variable \'ans\' to store the maximum product\n \n // Nested loops to iterate through pairs of elements in the \'nums\' array\n for (int i = 0; i < nums.size(); i++) {\n for (int j = i + 1; j < nums.size(); j++) {\n // Calculating the product of (nums[i] - 1) and (nums[j] - 1)\n // and updating \'ans\' to hold the maximum product found so far\n ans = max(ans, (nums[i] - 1) * (nums[j] - 1));\n }\n }\n \n return ans; // Returning the maximum product of two distinct elements\n }\n};\n\n\n\n```\n```C []\nint maxProduct(int nums[], int numsSize) {\n int ans = 0;\n \n for (int i = 0; i < numsSize; i++) {\n for (int j = i + 1; j < numsSize; j++) {\n ans = (ans > (nums[i] - 1) * (nums[j] - 1)) ? ans : (nums[i] - 1) * (nums[j] - 1);\n }\n }\n \n return ans;\n}\n\n\n\n```\n```Java []\n\nclass Solution {\n public int maxProduct(int[] nums) {\n int ans = 0;\n for (int i = 0; i < nums.length; i++) {\n for (int j = i + 1; j < nums.length; j++) {\n ans = Math.max(ans, (nums[i] - 1) * (nums[j] - 1));\n }\n }\n \n return ans;\n }\n}\n\n```\n```python3 []\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n ans = 0\n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n ans = max(ans, (nums[i] - 1) * (nums[j] - 1))\n \n return ans\n\n```\n\n```javascript []\nfunction maxProduct(nums) {\n let ans = 0;\n\n for (let i = 0; i < nums.length; i++) {\n for (let j = i + 1; j < nums.length; j++) {\n ans = Math.max(ans, (nums[i] - 1) * (nums[j] - 1));\n }\n }\n\n return ans;\n}\n\n```\n\n---\n\n#### ***Approach 2(Sorting)***\n1. The function sorts the input array `nums` in ascending order using `sort(nums.begin(), nums.end())`.\n1. It then retrieves the largest element (`x`) and the second largest element (`y`) from the sorted array.\n1. The function returns the product of `(x - 1) * (y - 1)`, which is the maximum possible product of two distinct elements in the array after subtracting 1 from each of the two largest elements.\n\n# Complexity\n- *Time complexity:*\n $$O(nlogn)$$\n \n\n- *Space complexity:*\n $$O(logn)$$ or $$O(n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n // Function to find the maximum product of two distinct elements in the \'nums\' array\n int maxProduct(vector<int>& nums) {\n sort(nums.begin(), nums.end()); // Sorting the \'nums\' array in ascending order\n \n int x = nums[nums.size() - 1]; // Getting the largest element\n int y = nums[nums.size() - 2]; // Getting the second largest element\n \n return (x - 1) * (y - 1); // Returning the product of (largest - 1) * (second largest - 1)\n }\n};\n\n\n\n```\n```C []\n\nint compare(const void *a, const void *b) {\n return (*(int*)a - *(int*)b);\n}\n\nint maxProduct(int* nums, int numsSize) {\n qsort(nums, numsSize, sizeof(int), compare);\n\n int x = nums[numsSize - 1];\n int y = nums[numsSize - 2];\n\n return (x - 1) * (y - 1);\n}\n\n\n```\n```Java []\nclass Solution {\n public int maxProduct(int[] nums) {\n Arrays.sort(nums);\n int x = nums[nums.length - 1];\n int y = nums[nums.length - 2];\n return (x - 1) * (y - 1);\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums.sort()\n x = nums[-1]\n y = nums[-2]\n return (x - 1) * (y - 1)\n\n```\n\n```javascript []\nfunction maxProduct(nums) {\n nums.sort((a, b) => a - b);\n\n const x = nums[nums.length - 1];\n const y = nums[nums.length - 2];\n\n return (x - 1) * (y - 1);\n}\n\n```\n\n---\n#### ***Approach 3(Second Biggest)***\n1. The function `maxProduct` iterates through each element (`num`) in the `nums` array.\n1. It maintains two variables, `biggest` and `secondBiggest`, to keep track of the largest and second largest numbers encountered in the array.\n1. If the current `num` is greater than the current `biggest`, it updates `secondBiggest` to the previous value of `biggest` and updates `biggest` to the current `num`.\n1. If the current `num` is not greater than `biggest`, it updates `secondBiggest` if necessary (keeping track of the second largest number encountered).\n1. Finally, it returns the product of `(biggest - 1) * (secondBiggest - 1)`, which is the maximum product of two distinct elements in the array after subtracting 1 from each of the two largest elements.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n // Function to find the maximum product of two distinct elements in the \'nums\' array\n int maxProduct(vector<int>& nums) {\n int biggest = 0; // Variable to store the largest number in \'nums\'\n int secondBiggest = 0; // Variable to store the second largest number in \'nums\'\n \n for (int num : nums) { // Iterating through each number in \'nums\'\n if (num > biggest) {\n // If the current number is greater than \'biggest\',\n // update \'secondBiggest\' and \'biggest\'\n secondBiggest = biggest;\n biggest = num;\n } else {\n // If the current number is not greater than \'biggest\',\n // update \'secondBiggest\' if necessary (keeping track of the second largest)\n secondBiggest = max(secondBiggest, num);\n }\n }\n \n return (biggest - 1) * (secondBiggest - 1); // Return the product of (biggest - 1) and (secondBiggest - 1)\n }\n};\n\n\n\n```\n```C []\nint maxProduct(int* nums, int numsSize) {\n int biggest = INT_MIN; // Variable to store the largest number in \'nums\'\n int secondBiggest = INT_MIN; // Variable to store the second largest number in \'nums\'\n\n for (int i = 0; i < numsSize; i++) { // Iterating through each number in \'nums\'\n if (nums[i] > biggest) {\n // If the current number is greater than \'biggest\',\n // update \'secondBiggest\' and \'biggest\'\n secondBiggest = biggest;\n biggest = nums[i];\n } else {\n // If the current number is not greater than \'biggest\',\n // update \'secondBiggest\' if necessary (keeping track of the second largest)\n secondBiggest = max(secondBiggest, nums[i]);\n }\n }\n\n return (biggest - 1) * (secondBiggest - 1); // Return the product of (biggest - 1) and (secondBiggest - 1)\n}\n\n\n\n```\n```Java []\nclass Solution {\n public int maxProduct(int[] nums) {\n int biggest = 0;\n int secondBiggest = 0;\n for (int num : nums) {\n if (num > biggest) {\n secondBiggest = biggest;\n biggest = num;\n } else {\n secondBiggest = Math.max(secondBiggest, num);\n }\n }\n \n return (biggest - 1) * (secondBiggest - 1);\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n biggest = 0\n second_biggest = 0\n for num in nums:\n if num > biggest:\n second_biggest = biggest\n biggest = num\n else:\n second_biggest = max(second_biggest, num)\n \n return (biggest - 1) * (second_biggest - 1)\n\n```\n\n```javascript []\nfunction maxProduct(nums) {\n let biggest = Number.MIN_SAFE_INTEGER; // Variable to store the largest number in \'nums\'\n let secondBiggest = Number.MIN_SAFE_INTEGER; // Variable to store the second largest number in \'nums\'\n\n for (let i = 0; i < nums.length; i++) { // Iterating through each number in \'nums\'\n if (nums[i] > biggest) {\n // If the current number is greater than \'biggest\',\n // update \'secondBiggest\' and \'biggest\'\n secondBiggest = biggest;\n biggest = nums[i];\n } else {\n // If the current number is not greater than \'biggest\',\n // update \'secondBiggest\' if necessary (keeping track of the second largest)\n secondBiggest = Math.max(secondBiggest, nums[i]);\n }\n }\n\n return (biggest - 1) * (secondBiggest - 1); // Return the product of (biggest - 1) and (secondBiggest - 1)\n}\n\n```\n\n---\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n--- | 21 | Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.
**Example 1:**
**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12.
**Example 2:**
**Input:** nums = \[1,5,4,5\]
**Output:** 16
**Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16.
**Example 3:**
**Input:** nums = \[3,7\]
**Output:** 12
**Constraints:**
* `2 <= nums.length <= 500`
* `1 <= nums[i] <= 10^3` | Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers. |
✅☑[C++/Java/Python/JavaScript] || 3 Approaches || Beats 100% || EXPLAINED🔥 | maximum-product-of-two-elements-in-an-array | 1 | 1 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Brute Force)***\n1. The function iterates through the elements in the `nums` array using two nested loops (`i` and `j`) to consider all possible pairs of elements.\n1. For each pair of elements (`nums[i], nums[j]`), it calculates the product of `(nums[i] - 1) * (nums[j] - 1)`.\n1. It updates the `ans` variable to hold the maximum product found among all pairs considered.\n1. Finally, it returns the maximum product of two distinct elements in the array.\n\n# Complexity\n- *Time complexity:*\n $$O(n^2)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n // Function to find the maximum product of two distinct elements in the \'nums\' array\n int maxProduct(vector<int>& nums) {\n int ans = 0; // Initializing the variable \'ans\' to store the maximum product\n \n // Nested loops to iterate through pairs of elements in the \'nums\' array\n for (int i = 0; i < nums.size(); i++) {\n for (int j = i + 1; j < nums.size(); j++) {\n // Calculating the product of (nums[i] - 1) and (nums[j] - 1)\n // and updating \'ans\' to hold the maximum product found so far\n ans = max(ans, (nums[i] - 1) * (nums[j] - 1));\n }\n }\n \n return ans; // Returning the maximum product of two distinct elements\n }\n};\n\n\n\n```\n```C []\nint maxProduct(int nums[], int numsSize) {\n int ans = 0;\n \n for (int i = 0; i < numsSize; i++) {\n for (int j = i + 1; j < numsSize; j++) {\n ans = (ans > (nums[i] - 1) * (nums[j] - 1)) ? ans : (nums[i] - 1) * (nums[j] - 1);\n }\n }\n \n return ans;\n}\n\n\n\n```\n```Java []\n\nclass Solution {\n public int maxProduct(int[] nums) {\n int ans = 0;\n for (int i = 0; i < nums.length; i++) {\n for (int j = i + 1; j < nums.length; j++) {\n ans = Math.max(ans, (nums[i] - 1) * (nums[j] - 1));\n }\n }\n \n return ans;\n }\n}\n\n```\n```python3 []\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n ans = 0\n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n ans = max(ans, (nums[i] - 1) * (nums[j] - 1))\n \n return ans\n\n```\n\n```javascript []\nfunction maxProduct(nums) {\n let ans = 0;\n\n for (let i = 0; i < nums.length; i++) {\n for (let j = i + 1; j < nums.length; j++) {\n ans = Math.max(ans, (nums[i] - 1) * (nums[j] - 1));\n }\n }\n\n return ans;\n}\n\n```\n\n---\n\n#### ***Approach 2(Sorting)***\n1. The function sorts the input array `nums` in ascending order using `sort(nums.begin(), nums.end())`.\n1. It then retrieves the largest element (`x`) and the second largest element (`y`) from the sorted array.\n1. The function returns the product of `(x - 1) * (y - 1)`, which is the maximum possible product of two distinct elements in the array after subtracting 1 from each of the two largest elements.\n\n# Complexity\n- *Time complexity:*\n $$O(nlogn)$$\n \n\n- *Space complexity:*\n $$O(logn)$$ or $$O(n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n // Function to find the maximum product of two distinct elements in the \'nums\' array\n int maxProduct(vector<int>& nums) {\n sort(nums.begin(), nums.end()); // Sorting the \'nums\' array in ascending order\n \n int x = nums[nums.size() - 1]; // Getting the largest element\n int y = nums[nums.size() - 2]; // Getting the second largest element\n \n return (x - 1) * (y - 1); // Returning the product of (largest - 1) * (second largest - 1)\n }\n};\n\n\n\n```\n```C []\n\nint compare(const void *a, const void *b) {\n return (*(int*)a - *(int*)b);\n}\n\nint maxProduct(int* nums, int numsSize) {\n qsort(nums, numsSize, sizeof(int), compare);\n\n int x = nums[numsSize - 1];\n int y = nums[numsSize - 2];\n\n return (x - 1) * (y - 1);\n}\n\n\n```\n```Java []\nclass Solution {\n public int maxProduct(int[] nums) {\n Arrays.sort(nums);\n int x = nums[nums.length - 1];\n int y = nums[nums.length - 2];\n return (x - 1) * (y - 1);\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums.sort()\n x = nums[-1]\n y = nums[-2]\n return (x - 1) * (y - 1)\n\n```\n\n```javascript []\nfunction maxProduct(nums) {\n nums.sort((a, b) => a - b);\n\n const x = nums[nums.length - 1];\n const y = nums[nums.length - 2];\n\n return (x - 1) * (y - 1);\n}\n\n```\n\n---\n#### ***Approach 3(Second Biggest)***\n1. The function `maxProduct` iterates through each element (`num`) in the `nums` array.\n1. It maintains two variables, `biggest` and `secondBiggest`, to keep track of the largest and second largest numbers encountered in the array.\n1. If the current `num` is greater than the current `biggest`, it updates `secondBiggest` to the previous value of `biggest` and updates `biggest` to the current `num`.\n1. If the current `num` is not greater than `biggest`, it updates `secondBiggest` if necessary (keeping track of the second largest number encountered).\n1. Finally, it returns the product of `(biggest - 1) * (secondBiggest - 1)`, which is the maximum product of two distinct elements in the array after subtracting 1 from each of the two largest elements.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n // Function to find the maximum product of two distinct elements in the \'nums\' array\n int maxProduct(vector<int>& nums) {\n int biggest = 0; // Variable to store the largest number in \'nums\'\n int secondBiggest = 0; // Variable to store the second largest number in \'nums\'\n \n for (int num : nums) { // Iterating through each number in \'nums\'\n if (num > biggest) {\n // If the current number is greater than \'biggest\',\n // update \'secondBiggest\' and \'biggest\'\n secondBiggest = biggest;\n biggest = num;\n } else {\n // If the current number is not greater than \'biggest\',\n // update \'secondBiggest\' if necessary (keeping track of the second largest)\n secondBiggest = max(secondBiggest, num);\n }\n }\n \n return (biggest - 1) * (secondBiggest - 1); // Return the product of (biggest - 1) and (secondBiggest - 1)\n }\n};\n\n\n\n```\n```C []\nint maxProduct(int* nums, int numsSize) {\n int biggest = INT_MIN; // Variable to store the largest number in \'nums\'\n int secondBiggest = INT_MIN; // Variable to store the second largest number in \'nums\'\n\n for (int i = 0; i < numsSize; i++) { // Iterating through each number in \'nums\'\n if (nums[i] > biggest) {\n // If the current number is greater than \'biggest\',\n // update \'secondBiggest\' and \'biggest\'\n secondBiggest = biggest;\n biggest = nums[i];\n } else {\n // If the current number is not greater than \'biggest\',\n // update \'secondBiggest\' if necessary (keeping track of the second largest)\n secondBiggest = max(secondBiggest, nums[i]);\n }\n }\n\n return (biggest - 1) * (secondBiggest - 1); // Return the product of (biggest - 1) and (secondBiggest - 1)\n}\n\n\n\n```\n```Java []\nclass Solution {\n public int maxProduct(int[] nums) {\n int biggest = 0;\n int secondBiggest = 0;\n for (int num : nums) {\n if (num > biggest) {\n secondBiggest = biggest;\n biggest = num;\n } else {\n secondBiggest = Math.max(secondBiggest, num);\n }\n }\n \n return (biggest - 1) * (secondBiggest - 1);\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n biggest = 0\n second_biggest = 0\n for num in nums:\n if num > biggest:\n second_biggest = biggest\n biggest = num\n else:\n second_biggest = max(second_biggest, num)\n \n return (biggest - 1) * (second_biggest - 1)\n\n```\n\n```javascript []\nfunction maxProduct(nums) {\n let biggest = Number.MIN_SAFE_INTEGER; // Variable to store the largest number in \'nums\'\n let secondBiggest = Number.MIN_SAFE_INTEGER; // Variable to store the second largest number in \'nums\'\n\n for (let i = 0; i < nums.length; i++) { // Iterating through each number in \'nums\'\n if (nums[i] > biggest) {\n // If the current number is greater than \'biggest\',\n // update \'secondBiggest\' and \'biggest\'\n secondBiggest = biggest;\n biggest = nums[i];\n } else {\n // If the current number is not greater than \'biggest\',\n // update \'secondBiggest\' if necessary (keeping track of the second largest)\n secondBiggest = Math.max(secondBiggest, nums[i]);\n }\n }\n\n return (biggest - 1) * (secondBiggest - 1); // Return the product of (biggest - 1) and (secondBiggest - 1)\n}\n\n```\n\n---\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n--- | 21 | Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**.
Return _the length of the shortest subarray to remove_.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,2,3,10,4,2,3,5\]
**Output:** 3
**Explanation:** The shortest subarray we can remove is \[10,4,2\] of length 3. The remaining elements after that will be \[1,2,3,3,5\] which are sorted.
Another correct solution is to remove the subarray \[3,10,4\].
**Example 2:**
**Input:** arr = \[5,4,3,2,1\]
**Output:** 4
**Explanation:** Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either \[5,4,3,2\] or \[4,3,2,1\].
**Example 3:**
**Input:** arr = \[1,2,3\]
**Output:** 0
**Explanation:** The array is already non-decreasing. We do not need to remove any elements.
**Constraints:**
* `1 <= arr.length <= 105`
* `0 <= arr[i] <= 109` | Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1). |
🚀🚀 Beats 100% | 0ms 🔥🔥 | maximum-product-of-two-elements-in-an-array | 1 | 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(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxProduct(vector<int>& nums) {\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n \n auto maxi1 = max_element(nums.begin(),nums.end());\n int index1 = maxi1 - nums.begin();\n int num1 = (nums[index1]);\n num1 = num1 - 1;\n cout << num1 << endl;\n nums.erase(nums.begin()+index1);\n int maxi2 = *max_element(nums.begin(),nums.end());\n maxi2 = maxi2 - 1;\n cout << maxi2 << endl;\n return (num1 * maxi2);\n }\n};\n``` | 3 | Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.
**Example 1:**
**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12.
**Example 2:**
**Input:** nums = \[1,5,4,5\]
**Output:** 16
**Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16.
**Example 3:**
**Input:** nums = \[3,7\]
**Output:** 12
**Constraints:**
* `2 <= nums.length <= 500`
* `1 <= nums[i] <= 10^3` | Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers. |
🚀🚀 Beats 100% | 0ms 🔥🔥 | maximum-product-of-two-elements-in-an-array | 1 | 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(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maxProduct(vector<int>& nums) {\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n \n auto maxi1 = max_element(nums.begin(),nums.end());\n int index1 = maxi1 - nums.begin();\n int num1 = (nums[index1]);\n num1 = num1 - 1;\n cout << num1 << endl;\n nums.erase(nums.begin()+index1);\n int maxi2 = *max_element(nums.begin(),nums.end());\n maxi2 = maxi2 - 1;\n cout << maxi2 << endl;\n return (num1 * maxi2);\n }\n};\n``` | 3 | Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**.
Return _the length of the shortest subarray to remove_.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,2,3,10,4,2,3,5\]
**Output:** 3
**Explanation:** The shortest subarray we can remove is \[10,4,2\] of length 3. The remaining elements after that will be \[1,2,3,3,5\] which are sorted.
Another correct solution is to remove the subarray \[3,10,4\].
**Example 2:**
**Input:** arr = \[5,4,3,2,1\]
**Output:** 4
**Explanation:** Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either \[5,4,3,2\] or \[4,3,2,1\].
**Example 3:**
**Input:** arr = \[1,2,3\]
**Output:** 0
**Explanation:** The array is already non-decreasing. We do not need to remove any elements.
**Constraints:**
* `1 <= arr.length <= 105`
* `0 <= arr[i] <= 109` | Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1). |
Python3 Solution | maximum-product-of-two-elements-in-an-array | 0 | 1 | \n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums.sort()\n return (nums[-1]-1)*(nums[-2]-1)\n``` | 3 | Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.
**Example 1:**
**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12.
**Example 2:**
**Input:** nums = \[1,5,4,5\]
**Output:** 16
**Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16.
**Example 3:**
**Input:** nums = \[3,7\]
**Output:** 12
**Constraints:**
* `2 <= nums.length <= 500`
* `1 <= nums[i] <= 10^3` | Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers. |
Python3 Solution | maximum-product-of-two-elements-in-an-array | 0 | 1 | \n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums.sort()\n return (nums[-1]-1)*(nums[-2]-1)\n``` | 3 | Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**.
Return _the length of the shortest subarray to remove_.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,2,3,10,4,2,3,5\]
**Output:** 3
**Explanation:** The shortest subarray we can remove is \[10,4,2\] of length 3. The remaining elements after that will be \[1,2,3,3,5\] which are sorted.
Another correct solution is to remove the subarray \[3,10,4\].
**Example 2:**
**Input:** arr = \[5,4,3,2,1\]
**Output:** 4
**Explanation:** Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either \[5,4,3,2\] or \[4,3,2,1\].
**Example 3:**
**Input:** arr = \[1,2,3\]
**Output:** 0
**Explanation:** The array is already non-decreasing. We do not need to remove any elements.
**Constraints:**
* `1 <= arr.length <= 105`
* `0 <= arr[i] <= 109` | Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1). |
Easy and simple soultion using python and java with explaination | maximum-product-of-two-elements-in-an-array | 1 | 1 | # Intuition\n\n\nThe problem involves finding the maximum product of two elements in an array. A potential approach is to sort the array and then multiply the two largest elements, which are the last two elements in the sorted array.\n\n# Approach\n\n\n1. Sort the array in ascending order.\n2. Subract last two elements with 1 \n3. Calculate the maximum product by multiplying the two largest elements, which are at the end of the sorted array.\n4. Return the result.\n\n# Complexity\n- Time complexity: O(n log n)\n\n- Space complexity: O(1) \n\n\n# Code\n```java []\nimport java.util.Arrays;\n\nclass Solution {\n public int maxProduct(int[] nums) {\n Arrays.sort(nums);\n return (nums[nums.length - 2] - 1) * (nums[nums.length - 1] - 1);\n }\n}\n\n```\n```python3 []\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums.sort()\n return ((nums[len(nums)-2]-1)*(nums[len(nums)-1]-1))\n```\n\n\n\n# Complexity\n- Time Complexity: O(n^2)\n\n- Space Complexity: O(1)\n\n# Code \n>this code is not effcient the above codes are effcient compared to this\n```python3 []\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n a = []\n for i in range(0, len(nums)):\n for j in range(i+1, len(nums)):\n a.append((nums[i] - 1) * (nums[j] - 1))\n return max(a)\n``` | 2 | Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.
**Example 1:**
**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12.
**Example 2:**
**Input:** nums = \[1,5,4,5\]
**Output:** 16
**Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16.
**Example 3:**
**Input:** nums = \[3,7\]
**Output:** 12
**Constraints:**
* `2 <= nums.length <= 500`
* `1 <= nums[i] <= 10^3` | Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers. |
Easy and simple soultion using python and java with explaination | maximum-product-of-two-elements-in-an-array | 1 | 1 | # Intuition\n\n\nThe problem involves finding the maximum product of two elements in an array. A potential approach is to sort the array and then multiply the two largest elements, which are the last two elements in the sorted array.\n\n# Approach\n\n\n1. Sort the array in ascending order.\n2. Subract last two elements with 1 \n3. Calculate the maximum product by multiplying the two largest elements, which are at the end of the sorted array.\n4. Return the result.\n\n# Complexity\n- Time complexity: O(n log n)\n\n- Space complexity: O(1) \n\n\n# Code\n```java []\nimport java.util.Arrays;\n\nclass Solution {\n public int maxProduct(int[] nums) {\n Arrays.sort(nums);\n return (nums[nums.length - 2] - 1) * (nums[nums.length - 1] - 1);\n }\n}\n\n```\n```python3 []\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums.sort()\n return ((nums[len(nums)-2]-1)*(nums[len(nums)-1]-1))\n```\n\n\n\n# Complexity\n- Time Complexity: O(n^2)\n\n- Space Complexity: O(1)\n\n# Code \n>this code is not effcient the above codes are effcient compared to this\n```python3 []\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n a = []\n for i in range(0, len(nums)):\n for j in range(i+1, len(nums)):\n a.append((nums[i] - 1) * (nums[j] - 1))\n return max(a)\n``` | 2 | Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**.
Return _the length of the shortest subarray to remove_.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,2,3,10,4,2,3,5\]
**Output:** 3
**Explanation:** The shortest subarray we can remove is \[10,4,2\] of length 3. The remaining elements after that will be \[1,2,3,3,5\] which are sorted.
Another correct solution is to remove the subarray \[3,10,4\].
**Example 2:**
**Input:** arr = \[5,4,3,2,1\]
**Output:** 4
**Explanation:** Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either \[5,4,3,2\] or \[4,3,2,1\].
**Example 3:**
**Input:** arr = \[1,2,3\]
**Output:** 0
**Explanation:** The array is already non-decreasing. We do not need to remove any elements.
**Constraints:**
* `1 <= arr.length <= 105`
* `0 <= arr[i] <= 109` | Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1). |
Try with Heap | Simple Solution | maximum-product-of-two-elements-in-an-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n heap = []\n for num in nums:\n heapq.heappush(heap, -num)\n max_val = -heapq.heappop(heap)\n second_max_val = -heapq.heappop(heap)\n return (max_val-1) * (second_max_val-1)\n``` | 2 | Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.
**Example 1:**
**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12.
**Example 2:**
**Input:** nums = \[1,5,4,5\]
**Output:** 16
**Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16.
**Example 3:**
**Input:** nums = \[3,7\]
**Output:** 12
**Constraints:**
* `2 <= nums.length <= 500`
* `1 <= nums[i] <= 10^3` | Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers. |
Try with Heap | Simple Solution | maximum-product-of-two-elements-in-an-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n heap = []\n for num in nums:\n heapq.heappush(heap, -num)\n max_val = -heapq.heappop(heap)\n second_max_val = -heapq.heappop(heap)\n return (max_val-1) * (second_max_val-1)\n``` | 2 | Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**.
Return _the length of the shortest subarray to remove_.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,2,3,10,4,2,3,5\]
**Output:** 3
**Explanation:** The shortest subarray we can remove is \[10,4,2\] of length 3. The remaining elements after that will be \[1,2,3,3,5\] which are sorted.
Another correct solution is to remove the subarray \[3,10,4\].
**Example 2:**
**Input:** arr = \[5,4,3,2,1\]
**Output:** 4
**Explanation:** Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either \[5,4,3,2\] or \[4,3,2,1\].
**Example 3:**
**Input:** arr = \[1,2,3\]
**Output:** 0
**Explanation:** The array is already non-decreasing. We do not need to remove any elements.
**Constraints:**
* `1 <= arr.length <= 105`
* `0 <= arr[i] <= 109` | Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1). |
O(n) Time complexity solution! (no sorting required) | maximum-product-of-two-elements-in-an-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* creating a negated list bcuz python by default offers min heap. so to get max element out of min heap we are multiplying the elements by -1.\n* pop two highest elements a & b.\n* return (a-1) * (b-1)\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n* creating negated list - O(n)\n* heapify operation - O(n)\n* heappop operation - O(2log n) , basically O(log n)\n* overall the dominant factor is O(n).\n* so the overall time complexity is O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Code\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums = [-i for i in nums]\n heapq.heapify(nums)\n a = heapq.heappop(nums) \n b = heapq.heappop(nums)\n return (abs(a)-1) * (abs(b)-1)\n \n``` | 2 | Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.
**Example 1:**
**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12.
**Example 2:**
**Input:** nums = \[1,5,4,5\]
**Output:** 16
**Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16.
**Example 3:**
**Input:** nums = \[3,7\]
**Output:** 12
**Constraints:**
* `2 <= nums.length <= 500`
* `1 <= nums[i] <= 10^3` | Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers. |
O(n) Time complexity solution! (no sorting required) | maximum-product-of-two-elements-in-an-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* creating a negated list bcuz python by default offers min heap. so to get max element out of min heap we are multiplying the elements by -1.\n* pop two highest elements a & b.\n* return (a-1) * (b-1)\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n* creating negated list - O(n)\n* heapify operation - O(n)\n* heappop operation - O(2log n) , basically O(log n)\n* overall the dominant factor is O(n).\n* so the overall time complexity is O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Code\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums = [-i for i in nums]\n heapq.heapify(nums)\n a = heapq.heappop(nums) \n b = heapq.heappop(nums)\n return (abs(a)-1) * (abs(b)-1)\n \n``` | 2 | Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**.
Return _the length of the shortest subarray to remove_.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,2,3,10,4,2,3,5\]
**Output:** 3
**Explanation:** The shortest subarray we can remove is \[10,4,2\] of length 3. The remaining elements after that will be \[1,2,3,3,5\] which are sorted.
Another correct solution is to remove the subarray \[3,10,4\].
**Example 2:**
**Input:** arr = \[5,4,3,2,1\]
**Output:** 4
**Explanation:** Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either \[5,4,3,2\] or \[4,3,2,1\].
**Example 3:**
**Input:** arr = \[1,2,3\]
**Output:** 0
**Explanation:** The array is already non-decreasing. We do not need to remove any elements.
**Constraints:**
* `1 <= arr.length <= 105`
* `0 <= arr[i] <= 109` | Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1). |
✅✅ One Liner ✅✅ beats 96.2% 🔥🥶 | maximum-product-of-two-elements-in-an-array | 0 | 1 | \n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGo through list to find two largest values, then compute solution\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\nRemove max from list (x2) and compute\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n return ((nums.pop(nums.index(max(nums)))) - 1) * ((nums.pop(nums.index(max(nums)))) - 1)\n```\n\n# Unpacked Code\nThis code is similar. It is actually more efficient because it only goes through the list once. However it is not one line \uD83E\uDD22\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n val1, val2 = 0, 0\n\n for num in nums:\n if num > val1:\n val1, val2 = num, val1\n elif num > val2:\n val2 = num\n return (val1 - 1) * (val2 - 1)\n``` | 1 | Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.
**Example 1:**
**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12.
**Example 2:**
**Input:** nums = \[1,5,4,5\]
**Output:** 16
**Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16.
**Example 3:**
**Input:** nums = \[3,7\]
**Output:** 12
**Constraints:**
* `2 <= nums.length <= 500`
* `1 <= nums[i] <= 10^3` | Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers. |
✅✅ One Liner ✅✅ beats 96.2% 🔥🥶 | maximum-product-of-two-elements-in-an-array | 0 | 1 | \n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGo through list to find two largest values, then compute solution\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\nRemove max from list (x2) and compute\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n return ((nums.pop(nums.index(max(nums)))) - 1) * ((nums.pop(nums.index(max(nums)))) - 1)\n```\n\n# Unpacked Code\nThis code is similar. It is actually more efficient because it only goes through the list once. However it is not one line \uD83E\uDD22\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n val1, val2 = 0, 0\n\n for num in nums:\n if num > val1:\n val1, val2 = num, val1\n elif num > val2:\n val2 = num\n return (val1 - 1) * (val2 - 1)\n``` | 1 | Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**.
Return _the length of the shortest subarray to remove_.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,2,3,10,4,2,3,5\]
**Output:** 3
**Explanation:** The shortest subarray we can remove is \[10,4,2\] of length 3. The remaining elements after that will be \[1,2,3,3,5\] which are sorted.
Another correct solution is to remove the subarray \[3,10,4\].
**Example 2:**
**Input:** arr = \[5,4,3,2,1\]
**Output:** 4
**Explanation:** Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either \[5,4,3,2\] or \[4,3,2,1\].
**Example 3:**
**Input:** arr = \[1,2,3\]
**Output:** 0
**Explanation:** The array is already non-decreasing. We do not need to remove any elements.
**Constraints:**
* `1 <= arr.length <= 105`
* `0 <= arr[i] <= 109` | Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1). |
Sidha-Sadha Solution🤞🤞🤞🤞 | maximum-product-of-two-elements-in-an-array | 0 | 1 | # Intuition\nFind 1st maximum and 2nd maximum .\nsubstract one from both and return their product\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\ninitialize max1 and max2 form first two element.\nRun for loop from 2 to length of array.\nUpdate max1 and max2 in each iteration if needed.\nsubstract 1 from both max1 and max2.\nReturn product of max1 and max2,\\.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n m1=max(nums[0],nums[1])\n m2=min(nums[0],nums[1])\n for i in range(2,len(nums)):\n if nums[i]>m1:\n m2=m1\n m1=nums[i]\n elif nums[i]>m2:\n m2=nums[i]\n \n return (m1-1)*(m2-1)\n \n``` | 1 | Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.
**Example 1:**
**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12.
**Example 2:**
**Input:** nums = \[1,5,4,5\]
**Output:** 16
**Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16.
**Example 3:**
**Input:** nums = \[3,7\]
**Output:** 12
**Constraints:**
* `2 <= nums.length <= 500`
* `1 <= nums[i] <= 10^3` | Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers. |
Sidha-Sadha Solution🤞🤞🤞🤞 | maximum-product-of-two-elements-in-an-array | 0 | 1 | # Intuition\nFind 1st maximum and 2nd maximum .\nsubstract one from both and return their product\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\ninitialize max1 and max2 form first two element.\nRun for loop from 2 to length of array.\nUpdate max1 and max2 in each iteration if needed.\nsubstract 1 from both max1 and max2.\nReturn product of max1 and max2,\\.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n m1=max(nums[0],nums[1])\n m2=min(nums[0],nums[1])\n for i in range(2,len(nums)):\n if nums[i]>m1:\n m2=m1\n m1=nums[i]\n elif nums[i]>m2:\n m2=nums[i]\n \n return (m1-1)*(m2-1)\n \n``` | 1 | Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**.
Return _the length of the shortest subarray to remove_.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,2,3,10,4,2,3,5\]
**Output:** 3
**Explanation:** The shortest subarray we can remove is \[10,4,2\] of length 3. The remaining elements after that will be \[1,2,3,3,5\] which are sorted.
Another correct solution is to remove the subarray \[3,10,4\].
**Example 2:**
**Input:** arr = \[5,4,3,2,1\]
**Output:** 4
**Explanation:** Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either \[5,4,3,2\] or \[4,3,2,1\].
**Example 3:**
**Input:** arr = \[1,2,3\]
**Output:** 0
**Explanation:** The array is already non-decreasing. We do not need to remove any elements.
**Constraints:**
* `1 <= arr.length <= 105`
* `0 <= arr[i] <= 109` | Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1). |
✅ 2 line solution || ✅ simple || ✅ python | maximum-product-of-two-elements-in-an-array | 0 | 1 | # Intuition\nThe problem asks for the maximum product of two distinct elements in the given list. Sorting the list in ascending order allows us to access the two largest elements at the end of the sorted list.\n\n\n# Approach\nThe approach involves sorting the input list in ascending order. After sorting, the two largest elements will be at the end of the list, and we can simply return the product of these two elements minus one.\n\n\n# Complexity\n- Time complexity:\nO(nlogn) - The dominant factor is the sorting operation, which has a time complexity of O(nlogn) for the average case.\n- Space complexity:\nO(1) - The space complexity is constant because the sorting is done in-place, and no additional space is used other than the input list.\n# Code\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums=sorted(nums)\n return (nums[-1]-1) * (nums[-2]-1)\n\n\n\n \n``` | 8 | Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.
**Example 1:**
**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12.
**Example 2:**
**Input:** nums = \[1,5,4,5\]
**Output:** 16
**Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16.
**Example 3:**
**Input:** nums = \[3,7\]
**Output:** 12
**Constraints:**
* `2 <= nums.length <= 500`
* `1 <= nums[i] <= 10^3` | Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers. |
✅ 2 line solution || ✅ simple || ✅ python | maximum-product-of-two-elements-in-an-array | 0 | 1 | # Intuition\nThe problem asks for the maximum product of two distinct elements in the given list. Sorting the list in ascending order allows us to access the two largest elements at the end of the sorted list.\n\n\n# Approach\nThe approach involves sorting the input list in ascending order. After sorting, the two largest elements will be at the end of the list, and we can simply return the product of these two elements minus one.\n\n\n# Complexity\n- Time complexity:\nO(nlogn) - The dominant factor is the sorting operation, which has a time complexity of O(nlogn) for the average case.\n- Space complexity:\nO(1) - The space complexity is constant because the sorting is done in-place, and no additional space is used other than the input list.\n# Code\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums=sorted(nums)\n return (nums[-1]-1) * (nums[-2]-1)\n\n\n\n \n``` | 8 | Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**.
Return _the length of the shortest subarray to remove_.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,2,3,10,4,2,3,5\]
**Output:** 3
**Explanation:** The shortest subarray we can remove is \[10,4,2\] of length 3. The remaining elements after that will be \[1,2,3,3,5\] which are sorted.
Another correct solution is to remove the subarray \[3,10,4\].
**Example 2:**
**Input:** arr = \[5,4,3,2,1\]
**Output:** 4
**Explanation:** Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either \[5,4,3,2\] or \[4,3,2,1\].
**Example 3:**
**Input:** arr = \[1,2,3\]
**Output:** 0
**Explanation:** The array is already non-decreasing. We do not need to remove any elements.
**Constraints:**
* `1 <= arr.length <= 105`
* `0 <= arr[i] <= 109` | Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1). |
Easiest Solution || Python using max | maximum-product-of-two-elements-in-an-array | 0 | 1 | # Intuition\nWe know that the answer will be the product of maximum and 2nd maximum.\nThus we find the maximum and store it then remove it to find the 2nd maximum.\n\n# Code\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n m1=max(nums)\n nums.remove(m1)\n m2=max(nums)\n return (m1-1)*(m2-1)\n```\n# **PLEASE DO UPVOTE!!!\uD83E\uDD79** | 1 | Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.
**Example 1:**
**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12.
**Example 2:**
**Input:** nums = \[1,5,4,5\]
**Output:** 16
**Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16.
**Example 3:**
**Input:** nums = \[3,7\]
**Output:** 12
**Constraints:**
* `2 <= nums.length <= 500`
* `1 <= nums[i] <= 10^3` | Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers. |
Easiest Solution || Python using max | maximum-product-of-two-elements-in-an-array | 0 | 1 | # Intuition\nWe know that the answer will be the product of maximum and 2nd maximum.\nThus we find the maximum and store it then remove it to find the 2nd maximum.\n\n# Code\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n m1=max(nums)\n nums.remove(m1)\n m2=max(nums)\n return (m1-1)*(m2-1)\n```\n# **PLEASE DO UPVOTE!!!\uD83E\uDD79** | 1 | Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**.
Return _the length of the shortest subarray to remove_.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,2,3,10,4,2,3,5\]
**Output:** 3
**Explanation:** The shortest subarray we can remove is \[10,4,2\] of length 3. The remaining elements after that will be \[1,2,3,3,5\] which are sorted.
Another correct solution is to remove the subarray \[3,10,4\].
**Example 2:**
**Input:** arr = \[5,4,3,2,1\]
**Output:** 4
**Explanation:** Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either \[5,4,3,2\] or \[4,3,2,1\].
**Example 3:**
**Input:** arr = \[1,2,3\]
**Output:** 0
**Explanation:** The array is already non-decreasing. We do not need to remove any elements.
**Constraints:**
* `1 <= arr.length <= 105`
* `0 <= arr[i] <= 109` | Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1). |
Simple solution with Sorting in Python3 | maximum-product-of-two-elements-in-an-array | 0 | 1 | # Intuition\nHere we have an array of integers `nums`.\nOur goal is to extract **maximum product** between two integers such as `(nums[i]-1)*(nums[j]-1)`\n\n# Approach \nSimply sort an array and take **two** largest integers.\n\n# Complexity\n- Time complexity: **O(N log N)**\n\n- Space complexity: **O(1)**\n\n# Code\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums.sort(reverse=True)\n\n return (nums[0] - 1) * (nums[1] - 1)\n``` | 1 | Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`.
**Example 1:**
**Input:** nums = \[3,4,5,2\]
**Output:** 12
**Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12.
**Example 2:**
**Input:** nums = \[1,5,4,5\]
**Output:** 16
**Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16.
**Example 3:**
**Input:** nums = \[3,7\]
**Output:** 12
**Constraints:**
* `2 <= nums.length <= 500`
* `1 <= nums[i] <= 10^3` | Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers. |
Simple solution with Sorting in Python3 | maximum-product-of-two-elements-in-an-array | 0 | 1 | # Intuition\nHere we have an array of integers `nums`.\nOur goal is to extract **maximum product** between two integers such as `(nums[i]-1)*(nums[j]-1)`\n\n# Approach \nSimply sort an array and take **two** largest integers.\n\n# Complexity\n- Time complexity: **O(N log N)**\n\n- Space complexity: **O(1)**\n\n# Code\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums.sort(reverse=True)\n\n return (nums[0] - 1) * (nums[1] - 1)\n``` | 1 | Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**.
Return _the length of the shortest subarray to remove_.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,2,3,10,4,2,3,5\]
**Output:** 3
**Explanation:** The shortest subarray we can remove is \[10,4,2\] of length 3. The remaining elements after that will be \[1,2,3,3,5\] which are sorted.
Another correct solution is to remove the subarray \[3,10,4\].
**Example 2:**
**Input:** arr = \[5,4,3,2,1\]
**Output:** 4
**Explanation:** Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either \[5,4,3,2\] or \[4,3,2,1\].
**Example 3:**
**Input:** arr = \[1,2,3\]
**Output:** 0
**Explanation:** The array is already non-decreasing. We do not need to remove any elements.
**Constraints:**
* `1 <= arr.length <= 105`
* `0 <= arr[i] <= 109` | Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1). |
Python easy solution | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | 0 | 1 | ```\nclass Solution:\n def maxArea(self, h: int, w: int, hc: List[int], vc: List[int]) -> int:\n \n hc.sort()\n vc.sort()\n \n maxh = hc[0]\n maxv = vc[0]\n \n for i in range(1, len(hc)):\n maxh = max(maxh, hc[i] - hc[i-1])\n maxh = max(maxh, h - hc[-1])\n \n for i in range(1, len(vc)):\n maxv = max(maxv, vc[i] - vc[i-1])\n maxv = max(maxv, w - vc[-1])\n \n return maxh*maxv % (10**9 + 7)\n``` | 3 | You are given a rectangular cake of size `h x w` and two arrays of integers `horizontalCuts` and `verticalCuts` where:
* `horizontalCuts[i]` is the distance from the top of the rectangular cake to the `ith` horizontal cut and similarly, and
* `verticalCuts[j]` is the distance from the left of the rectangular cake to the `jth` vertical cut.
Return _the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays_ `horizontalCuts` _and_ `verticalCuts`. Since the answer can be a large number, return this **modulo** `109 + 7`.
**Example 1:**
**Input:** h = 5, w = 4, horizontalCuts = \[1,2,4\], verticalCuts = \[1,3\]
**Output:** 4
**Explanation:** The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.
**Example 2:**
**Input:** h = 5, w = 4, horizontalCuts = \[3,1\], verticalCuts = \[1\]
**Output:** 6
**Explanation:** The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.
**Example 3:**
**Input:** h = 5, w = 4, horizontalCuts = \[3\], verticalCuts = \[3\]
**Output:** 9
**Constraints:**
* `2 <= h, w <= 109`
* `1 <= horizontalCuts.length <= min(h - 1, 105)`
* `1 <= verticalCuts.length <= min(w - 1, 105)`
* `1 <= horizontalCuts[i] < h`
* `1 <= verticalCuts[i] < w`
* All the elements in `horizontalCuts` are distinct.
* All the elements in `verticalCuts` are distinct. | If we know the sum of a subtree, the answer is max( (total_sum - subtree_sum) * subtree_sum) in each node. |
Python easy solution | maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts | 0 | 1 | ```\nclass Solution:\n def maxArea(self, h: int, w: int, hc: List[int], vc: List[int]) -> int:\n \n hc.sort()\n vc.sort()\n \n maxh = hc[0]\n maxv = vc[0]\n \n for i in range(1, len(hc)):\n maxh = max(maxh, hc[i] - hc[i-1])\n maxh = max(maxh, h - hc[-1])\n \n for i in range(1, len(vc)):\n maxv = max(maxv, vc[i] - vc[i-1])\n maxv = max(maxv, w - vc[-1])\n \n return maxh*maxv % (10**9 + 7)\n``` | 3 | You are given an array of **distinct** positive integers locations where `locations[i]` represents the position of city `i`. You are also given integers `start`, `finish` and `fuel` representing the starting city, ending city, and the initial amount of fuel you have, respectively.
At each step, if you are at city `i`, you can pick any city `j` such that `j != i` and `0 <= j < locations.length` and move to city `j`. Moving from city `i` to city `j` reduces the amount of fuel you have by `|locations[i] - locations[j]|`. Please notice that `|x|` denotes the absolute value of `x`.
Notice that `fuel` **cannot** become negative at any point in time, and that you are **allowed** to visit any city more than once (including `start` and `finish`).
Return _the count of all possible routes from_ `start` _to_ `finish`. Since the answer may be too large, return it modulo `109 + 7`.
**Example 1:**
**Input:** locations = \[2,3,6,8,4\], start = 1, finish = 3, fuel = 5
**Output:** 4
**Explanation:** The following are all possible routes, each uses 5 units of fuel:
1 -> 3
1 -> 2 -> 3
1 -> 4 -> 3
1 -> 4 -> 2 -> 3
**Example 2:**
**Input:** locations = \[4,3,1\], start = 1, finish = 0, fuel = 6
**Output:** 5
**Explanation:** The following are all possible routes:
1 -> 0, used fuel = 1
1 -> 2 -> 0, used fuel = 5
1 -> 2 -> 1 -> 0, used fuel = 5
1 -> 0 -> 1 -> 0, used fuel = 3
1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5
**Example 3:**
**Input:** locations = \[5,2,1\], start = 0, finish = 2, fuel = 3
**Output:** 0
**Explanation:** It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.
**Constraints:**
* `2 <= locations.length <= 100`
* `1 <= locations[i] <= 109`
* All integers in `locations` are **distinct**.
* `0 <= start, finish < locations.length`
* `1 <= fuel <= 200` | Sort the arrays, then compute the maximum difference between two consecutive elements for horizontal cuts and vertical cuts. The answer is the product of these maximum values in horizontal cuts and vertical cuts. |
Python O(E) bfs solution | reorder-routes-to-make-all-paths-lead-to-the-city-zero | 0 | 1 | \n\n\n```\n def minReorder(self, n: int, connections: List[List[int]]) -> int:\n graph = [ [] for i in range(0,n)]\n\n for item in connections:\n graph[item[0]].append( [item[1],0] )\n graph[item[1]].append( [item[0],1] )\n\n dq = deque()\n dq.append(0)\n visited = [0 for i in range(0,n)]\n visited[0] = 1\n res = 0\n while(len(dq)>0):\n v = dq.popleft()\n for neib,neg in graph[v]:\n if(visited[neib] == 0 ):\n visited[neib] = 1\n dq.append(neib);\n if(neg): res += 1\n return n-1-res\n\n``` | 2 | There are `n` cities numbered from `0` to `n - 1` and `n - 1` roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.
Roads are represented by `connections` where `connections[i] = [ai, bi]` represents a road from city `ai` to city `bi`.
This year, there will be a big event in the capital (city `0`), and many people want to travel to this city.
Your task consists of reorienting some roads such that each city can visit the city `0`. Return the **minimum** number of edges changed.
It's **guaranteed** that each city can reach city `0` after reorder.
**Example 1:**
**Input:** n = 6, connections = \[\[0,1\],\[1,3\],\[2,3\],\[4,0\],\[4,5\]\]
**Output:** 3
**Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital).
**Example 2:**
**Input:** n = 5, connections = \[\[1,0\],\[1,2\],\[3,2\],\[3,4\]\]
**Output:** 2
**Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital).
**Example 3:**
**Input:** n = 3, connections = \[\[1,0\],\[2,0\]\]
**Output:** 0
**Constraints:**
* `2 <= n <= 5 * 104`
* `connections.length == n - 1`
* `connections[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi` | Use dynamic programming. dp[i] is max jumps you can do starting from index i. Answer is max(dp[i]). dp[i] = 1 + max (dp[j]) where j is all indices you can reach from i. |
Python O(E) bfs solution | reorder-routes-to-make-all-paths-lead-to-the-city-zero | 0 | 1 | \n\n\n```\n def minReorder(self, n: int, connections: List[List[int]]) -> int:\n graph = [ [] for i in range(0,n)]\n\n for item in connections:\n graph[item[0]].append( [item[1],0] )\n graph[item[1]].append( [item[0],1] )\n\n dq = deque()\n dq.append(0)\n visited = [0 for i in range(0,n)]\n visited[0] = 1\n res = 0\n while(len(dq)>0):\n v = dq.popleft()\n for neib,neg in graph[v]:\n if(visited[neib] == 0 ):\n visited[neib] = 1\n dq.append(neib);\n if(neg): res += 1\n return n-1-res\n\n``` | 2 | Given a string `s` containing only lowercase English letters and the `'?'` character, convert **all** the `'?'` characters into lowercase letters such that the final string does not contain any **consecutive repeating** characters. You **cannot** modify the non `'?'` characters.
It is **guaranteed** that there are no consecutive repeating characters in the given string **except** for `'?'`.
Return _the final string after all the conversions (possibly zero) have been made_. If there is more than one solution, return **any of them**. It can be shown that an answer is always possible with the given constraints.
**Example 1:**
**Input:** s = "?zs "
**Output:** "azs "
**Explanation:** There are 25 solutions for this problem. From "azs " to "yzs ", all are valid. Only "z " is an invalid modification as the string will consist of consecutive repeating characters in "zzs ".
**Example 2:**
**Input:** s = "ubv?w "
**Output:** "ubvaw "
**Explanation:** There are 24 solutions for this problem. Only "v " and "w " are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw " and "ubvww ".
**Constraints:**
* `1 <= s.length <= 100`
* `s` consist of lowercase English letters and `'?'`. | Treat the graph as undirected. Start a dfs from the root, if you come across an edge in the forward direction, you need to reverse the edge. |
Python short and clean. DFS. Functional programming. | reorder-routes-to-make-all-paths-lead-to-the-city-zero | 0 | 1 | # Approach\nTL;DR, Same as [Official solution](https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/editorial/).\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```python\nclass Solution:\n def minReorder(self, n: int, connections: list[list[int]]) -> int:\n T = Hashable\n Direction = bool\n Graph = Mapping[T, Iterable[tuple[T, Direction]]]\n\n def min_flips(graph: Graph, u: T, parent: T | None = None) -> int:\n return sum(min_flips(graph, v, u) + d for v, d in graph[u] if v != parent)\n\n g = defaultdict(list)\n for u, v in connections: g[u].append((v, True)); g[v].append((u, False))\n return min_flips(g, 0)\n\n\n``` | 2 | There are `n` cities numbered from `0` to `n - 1` and `n - 1` roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.
Roads are represented by `connections` where `connections[i] = [ai, bi]` represents a road from city `ai` to city `bi`.
This year, there will be a big event in the capital (city `0`), and many people want to travel to this city.
Your task consists of reorienting some roads such that each city can visit the city `0`. Return the **minimum** number of edges changed.
It's **guaranteed** that each city can reach city `0` after reorder.
**Example 1:**
**Input:** n = 6, connections = \[\[0,1\],\[1,3\],\[2,3\],\[4,0\],\[4,5\]\]
**Output:** 3
**Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital).
**Example 2:**
**Input:** n = 5, connections = \[\[1,0\],\[1,2\],\[3,2\],\[3,4\]\]
**Output:** 2
**Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital).
**Example 3:**
**Input:** n = 3, connections = \[\[1,0\],\[2,0\]\]
**Output:** 0
**Constraints:**
* `2 <= n <= 5 * 104`
* `connections.length == n - 1`
* `connections[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi` | Use dynamic programming. dp[i] is max jumps you can do starting from index i. Answer is max(dp[i]). dp[i] = 1 + max (dp[j]) where j is all indices you can reach from i. |
Python short and clean. DFS. Functional programming. | reorder-routes-to-make-all-paths-lead-to-the-city-zero | 0 | 1 | # Approach\nTL;DR, Same as [Official solution](https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/editorial/).\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```python\nclass Solution:\n def minReorder(self, n: int, connections: list[list[int]]) -> int:\n T = Hashable\n Direction = bool\n Graph = Mapping[T, Iterable[tuple[T, Direction]]]\n\n def min_flips(graph: Graph, u: T, parent: T | None = None) -> int:\n return sum(min_flips(graph, v, u) + d for v, d in graph[u] if v != parent)\n\n g = defaultdict(list)\n for u, v in connections: g[u].append((v, True)); g[v].append((u, False))\n return min_flips(g, 0)\n\n\n``` | 2 | Given a string `s` containing only lowercase English letters and the `'?'` character, convert **all** the `'?'` characters into lowercase letters such that the final string does not contain any **consecutive repeating** characters. You **cannot** modify the non `'?'` characters.
It is **guaranteed** that there are no consecutive repeating characters in the given string **except** for `'?'`.
Return _the final string after all the conversions (possibly zero) have been made_. If there is more than one solution, return **any of them**. It can be shown that an answer is always possible with the given constraints.
**Example 1:**
**Input:** s = "?zs "
**Output:** "azs "
**Explanation:** There are 25 solutions for this problem. From "azs " to "yzs ", all are valid. Only "z " is an invalid modification as the string will consist of consecutive repeating characters in "zzs ".
**Example 2:**
**Input:** s = "ubv?w "
**Output:** "ubvaw "
**Explanation:** There are 24 solutions for this problem. Only "v " and "w " are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw " and "ubvww ".
**Constraints:**
* `1 <= s.length <= 100`
* `s` consist of lowercase English letters and `'?'`. | Treat the graph as undirected. Start a dfs from the root, if you come across an edge in the forward direction, you need to reverse the edge. |
Simple python solution using BFS traversal | reorder-routes-to-make-all-paths-lead-to-the-city-zero | 0 | 1 | ```\nclass Solution:\n def minReorder(self, n: int, connections: List[List[int]]) -> int:\n visited=[0]*n\n indegree=[[] for _ in range(n)]\n outdegree=[[] for _ in range(n)]\n for frm,to in connections:\n indegree[to].append(frm)\n outdegree[frm].append(to)\n lst=[0]\n visited[0]=1\n ct=0\n while lst:\n x=lst.pop(0)\n for i in indegree[x]:\n if visited[i]==0:\n lst.append(i)\n visited[i]=1\n for i in outdegree[x]:\n if visited[i]==0:\n lst.append(i)\n visited[i]=1\n # here we have to change the direction of edge\n ct+=1\n return ct\n``` | 3 | There are `n` cities numbered from `0` to `n - 1` and `n - 1` roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.
Roads are represented by `connections` where `connections[i] = [ai, bi]` represents a road from city `ai` to city `bi`.
This year, there will be a big event in the capital (city `0`), and many people want to travel to this city.
Your task consists of reorienting some roads such that each city can visit the city `0`. Return the **minimum** number of edges changed.
It's **guaranteed** that each city can reach city `0` after reorder.
**Example 1:**
**Input:** n = 6, connections = \[\[0,1\],\[1,3\],\[2,3\],\[4,0\],\[4,5\]\]
**Output:** 3
**Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital).
**Example 2:**
**Input:** n = 5, connections = \[\[1,0\],\[1,2\],\[3,2\],\[3,4\]\]
**Output:** 2
**Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital).
**Example 3:**
**Input:** n = 3, connections = \[\[1,0\],\[2,0\]\]
**Output:** 0
**Constraints:**
* `2 <= n <= 5 * 104`
* `connections.length == n - 1`
* `connections[i].length == 2`
* `0 <= ai, bi <= n - 1`
* `ai != bi` | Use dynamic programming. dp[i] is max jumps you can do starting from index i. Answer is max(dp[i]). dp[i] = 1 + max (dp[j]) where j is all indices you can reach from i. |
Simple python solution using BFS traversal | reorder-routes-to-make-all-paths-lead-to-the-city-zero | 0 | 1 | ```\nclass Solution:\n def minReorder(self, n: int, connections: List[List[int]]) -> int:\n visited=[0]*n\n indegree=[[] for _ in range(n)]\n outdegree=[[] for _ in range(n)]\n for frm,to in connections:\n indegree[to].append(frm)\n outdegree[frm].append(to)\n lst=[0]\n visited[0]=1\n ct=0\n while lst:\n x=lst.pop(0)\n for i in indegree[x]:\n if visited[i]==0:\n lst.append(i)\n visited[i]=1\n for i in outdegree[x]:\n if visited[i]==0:\n lst.append(i)\n visited[i]=1\n # here we have to change the direction of edge\n ct+=1\n return ct\n``` | 3 | Given a string `s` containing only lowercase English letters and the `'?'` character, convert **all** the `'?'` characters into lowercase letters such that the final string does not contain any **consecutive repeating** characters. You **cannot** modify the non `'?'` characters.
It is **guaranteed** that there are no consecutive repeating characters in the given string **except** for `'?'`.
Return _the final string after all the conversions (possibly zero) have been made_. If there is more than one solution, return **any of them**. It can be shown that an answer is always possible with the given constraints.
**Example 1:**
**Input:** s = "?zs "
**Output:** "azs "
**Explanation:** There are 25 solutions for this problem. From "azs " to "yzs ", all are valid. Only "z " is an invalid modification as the string will consist of consecutive repeating characters in "zzs ".
**Example 2:**
**Input:** s = "ubv?w "
**Output:** "ubvaw "
**Explanation:** There are 24 solutions for this problem. Only "v " and "w " are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw " and "ubvww ".
**Constraints:**
* `1 <= s.length <= 100`
* `s` consist of lowercase English letters and `'?'`. | Treat the graph as undirected. Start a dfs from the root, if you come across an edge in the forward direction, you need to reverse the edge. |
Backtracking py3 | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | 0 | 1 | ```\nclass Solution:\n def getProbability(self, balls: List[int]) -> float:\n n = sum(balls)\n self.boxa = [0 for a in balls]\n self.boxb = [0 for a in balls]\n self.total = 0\n self.valid = 0\n m = len(balls)\n def dfs(i): # processing the ith color \n if sum(self.boxa) == n // 2 and sum(self.boxb) == n // 2:\n counta = factorial(n // 2) \n countb = factorial(n // 2) \n for a in self.boxa:\n counta /= factorial(a)\n for b in self.boxb:\n countb /= factorial(b) # permutations of colors in a box count differently\n self.total += counta * countb\n na = sum(1 for a in self.boxa if a > 0)\n nb = sum(1 for b in self.boxb if b > 0)\n if na == nb: self.valid += counta * countb\n return\n if i == m:\n return\n for j in range(balls[i]+1):\n if j + sum(self.boxa) <= n // 2 and balls[i] - j + sum(self.boxb) <= n // 2:\n self.boxa[i] += j\n self.boxb[i] += balls[i] - j\n dfs(i+1)\n self.boxa[i] -= j\n self.boxb[i] -= balls[i] - j\n \n dfs(0)\n return self.valid / self.total\n\n\n\n \n``` | 0 | Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`.
All the balls will be **shuffled uniformly at random**, then we will distribute the first `n` balls to the first box and the remaining `n` balls to the other box (Please read the explanation of the second example carefully).
Please note that the two boxes are considered different. For example, if we have two balls of colors `a` and `b`, and two boxes `[]` and `()`, then the distribution `[a] (b)` is considered different than the distribution `[b] (a)` (Please read the explanation of the first example carefully).
Return _the probability_ that the two boxes have the same number of distinct balls. Answers within `10-5` of the actual value will be accepted as correct.
**Example 1:**
**Input:** balls = \[1,1\]
**Output:** 1.00000
**Explanation:** Only 2 ways to divide the balls equally:
- A ball of color 1 to box 1 and a ball of color 2 to box 2
- A ball of color 2 to box 1 and a ball of color 1 to box 2
In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1
**Example 2:**
**Input:** balls = \[2,1,1\]
**Output:** 0.66667
**Explanation:** We have the set of balls \[1, 1, 2, 3\]
This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):
\[1,1 / 2,3\], \[1,1 / 3,2\], \[1,2 / 1,3\], \[1,2 / 3,1\], \[1,3 / 1,2\], \[1,3 / 2,1\], \[2,1 / 1,3\], \[2,1 / 3,1\], \[2,3 / 1,1\], \[3,1 / 1,2\], \[3,1 / 2,1\], \[3,2 / 1,1\]
After that, we add the first two balls to the first box and the second two balls to the second box.
We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.
Probability is 8/12 = 0.66667
**Example 3:**
**Input:** balls = \[1,2,1,2\]
**Output:** 0.60000
**Explanation:** The set of balls is \[1, 2, 2, 3, 4, 4\]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.
Probability = 108 / 180 = 0.6
**Constraints:**
* `1 <= balls.length <= 8`
* `1 <= balls[i] <= 6`
* `sum(balls)` is even. | null |
Backtracking py3 | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | 0 | 1 | ```\nclass Solution:\n def getProbability(self, balls: List[int]) -> float:\n n = sum(balls)\n self.boxa = [0 for a in balls]\n self.boxb = [0 for a in balls]\n self.total = 0\n self.valid = 0\n m = len(balls)\n def dfs(i): # processing the ith color \n if sum(self.boxa) == n // 2 and sum(self.boxb) == n // 2:\n counta = factorial(n // 2) \n countb = factorial(n // 2) \n for a in self.boxa:\n counta /= factorial(a)\n for b in self.boxb:\n countb /= factorial(b) # permutations of colors in a box count differently\n self.total += counta * countb\n na = sum(1 for a in self.boxa if a > 0)\n nb = sum(1 for b in self.boxb if b > 0)\n if na == nb: self.valid += counta * countb\n return\n if i == m:\n return\n for j in range(balls[i]+1):\n if j + sum(self.boxa) <= n // 2 and balls[i] - j + sum(self.boxb) <= n // 2:\n self.boxa[i] += j\n self.boxb[i] += balls[i] - j\n dfs(i+1)\n self.boxa[i] -= j\n self.boxb[i] -= balls[i] - j\n \n dfs(0)\n return self.valid / self.total\n\n\n\n \n``` | 0 | Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules:
* Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k < nums2.length`.
* Type 2: Triplet (i, j, k) if `nums2[i]2 == nums1[j] * nums1[k]` where `0 <= i < nums2.length` and `0 <= j < k < nums1.length`.
**Example 1:**
**Input:** nums1 = \[7,4\], nums2 = \[5,2,8,9\]
**Output:** 1
**Explanation:** Type 1: (1, 1, 2), nums1\[1\]2 = nums2\[1\] \* nums2\[2\]. (42 = 2 \* 8).
**Example 2:**
**Input:** nums1 = \[1,1\], nums2 = \[1,1,1\]
**Output:** 9
**Explanation:** All Triplets are valid, because 12 = 1 \* 1.
Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1\[i\]2 = nums2\[j\] \* nums2\[k\].
Type 2: (0,0,1), (1,0,1), (2,0,1). nums2\[i\]2 = nums1\[j\] \* nums1\[k\].
**Example 3:**
**Input:** nums1 = \[7,7,8,3\], nums2 = \[1,2,9,7\]
**Output:** 2
**Explanation:** There are 2 valid triplets.
Type 1: (3,0,2). nums1\[3\]2 = nums2\[0\] \* nums2\[2\].
Type 2: (3,0,1). nums2\[3\]2 = nums1\[0\] \* nums1\[1\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `1 <= nums1[i], nums2[i] <= 105` | Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of a draw is the sigma of probabilities of different ways to achieve draw. Can you use Dynamic programming to solve this problem in a better complexity ? |
Python | complicated Solution | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | 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```\n\nclass Solution:\n def getProbability(self, balls: List[int]) -> float:\n def fact(n):\n if n <= 0:return 1\n return n*fact(n-1)\n t = 2**len(balls)\n tm = len(balls)\n res = 0\n ed = sum(balls)//2\n gt = fact(ed)\n def go(arr):\n ans = gt*gt\n for x in range(tm):\n ans /= fact(arr[x])\n ans /= fact(abs(balls[x]-arr[x]))\n return ans\n def solve(i,l,r,cntl,arr):\n nonlocal res, gets\n if cntl>ed:\n return \n if i == tm:\n if cntl == ed:\n res+=go(arr)\n return\n if (1<<i)&l != 0 and (1<<i)&r != 0:\n for j in range(1,balls[i]):\n arr[i] = j\n solve(i+1, l,r, cntl+j, arr)\n arr[i] = 0\n elif (1<<i)&l != 0:\n arr[i] = balls[i]\n solve(i+1, l, r, cntl+balls[i], arr)\n arr[i] = 0\n else:\n solve(i+1, l, r, cntl, arr)\n cnt = 0 \n temp = [0 for i in range(tm)]\n for i in range(t):\n for j in range(t):\n if bin(i|j).count("1") == tm and bin(i).count("1") == bin(j).count("1"):\n solve(0,i,j,0,temp)\n gets = fact(ed*2)\n for i in balls:\n gets /= fact(i) \n return res/gets\n``` | 0 | Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`.
All the balls will be **shuffled uniformly at random**, then we will distribute the first `n` balls to the first box and the remaining `n` balls to the other box (Please read the explanation of the second example carefully).
Please note that the two boxes are considered different. For example, if we have two balls of colors `a` and `b`, and two boxes `[]` and `()`, then the distribution `[a] (b)` is considered different than the distribution `[b] (a)` (Please read the explanation of the first example carefully).
Return _the probability_ that the two boxes have the same number of distinct balls. Answers within `10-5` of the actual value will be accepted as correct.
**Example 1:**
**Input:** balls = \[1,1\]
**Output:** 1.00000
**Explanation:** Only 2 ways to divide the balls equally:
- A ball of color 1 to box 1 and a ball of color 2 to box 2
- A ball of color 2 to box 1 and a ball of color 1 to box 2
In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1
**Example 2:**
**Input:** balls = \[2,1,1\]
**Output:** 0.66667
**Explanation:** We have the set of balls \[1, 1, 2, 3\]
This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):
\[1,1 / 2,3\], \[1,1 / 3,2\], \[1,2 / 1,3\], \[1,2 / 3,1\], \[1,3 / 1,2\], \[1,3 / 2,1\], \[2,1 / 1,3\], \[2,1 / 3,1\], \[2,3 / 1,1\], \[3,1 / 1,2\], \[3,1 / 2,1\], \[3,2 / 1,1\]
After that, we add the first two balls to the first box and the second two balls to the second box.
We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.
Probability is 8/12 = 0.66667
**Example 3:**
**Input:** balls = \[1,2,1,2\]
**Output:** 0.60000
**Explanation:** The set of balls is \[1, 2, 2, 3, 4, 4\]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.
Probability = 108 / 180 = 0.6
**Constraints:**
* `1 <= balls.length <= 8`
* `1 <= balls[i] <= 6`
* `sum(balls)` is even. | null |
Python | complicated Solution | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | 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```\n\nclass Solution:\n def getProbability(self, balls: List[int]) -> float:\n def fact(n):\n if n <= 0:return 1\n return n*fact(n-1)\n t = 2**len(balls)\n tm = len(balls)\n res = 0\n ed = sum(balls)//2\n gt = fact(ed)\n def go(arr):\n ans = gt*gt\n for x in range(tm):\n ans /= fact(arr[x])\n ans /= fact(abs(balls[x]-arr[x]))\n return ans\n def solve(i,l,r,cntl,arr):\n nonlocal res, gets\n if cntl>ed:\n return \n if i == tm:\n if cntl == ed:\n res+=go(arr)\n return\n if (1<<i)&l != 0 and (1<<i)&r != 0:\n for j in range(1,balls[i]):\n arr[i] = j\n solve(i+1, l,r, cntl+j, arr)\n arr[i] = 0\n elif (1<<i)&l != 0:\n arr[i] = balls[i]\n solve(i+1, l, r, cntl+balls[i], arr)\n arr[i] = 0\n else:\n solve(i+1, l, r, cntl, arr)\n cnt = 0 \n temp = [0 for i in range(tm)]\n for i in range(t):\n for j in range(t):\n if bin(i|j).count("1") == tm and bin(i).count("1") == bin(j).count("1"):\n solve(0,i,j,0,temp)\n gets = fact(ed*2)\n for i in balls:\n gets /= fact(i) \n return res/gets\n``` | 0 | Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules:
* Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k < nums2.length`.
* Type 2: Triplet (i, j, k) if `nums2[i]2 == nums1[j] * nums1[k]` where `0 <= i < nums2.length` and `0 <= j < k < nums1.length`.
**Example 1:**
**Input:** nums1 = \[7,4\], nums2 = \[5,2,8,9\]
**Output:** 1
**Explanation:** Type 1: (1, 1, 2), nums1\[1\]2 = nums2\[1\] \* nums2\[2\]. (42 = 2 \* 8).
**Example 2:**
**Input:** nums1 = \[1,1\], nums2 = \[1,1,1\]
**Output:** 9
**Explanation:** All Triplets are valid, because 12 = 1 \* 1.
Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1\[i\]2 = nums2\[j\] \* nums2\[k\].
Type 2: (0,0,1), (1,0,1), (2,0,1). nums2\[i\]2 = nums1\[j\] \* nums1\[k\].
**Example 3:**
**Input:** nums1 = \[7,7,8,3\], nums2 = \[1,2,9,7\]
**Output:** 2
**Explanation:** There are 2 valid triplets.
Type 1: (3,0,2). nums1\[3\]2 = nums2\[0\] \* nums2\[2\].
Type 2: (3,0,1). nums2\[3\]2 = nums1\[0\] \* nums1\[1\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `1 <= nums1[i], nums2[i] <= 105` | Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of a draw is the sigma of probabilities of different ways to achieve draw. Can you use Dynamic programming to solve this problem in a better complexity ? |
Object Oriented for Memory Optimization | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can consider a dynamic programming approach concerning a valid combination. \nA valid combination is one in which all colors have been used, there are no left overs of a color, and both buckets have an equal number of distinct colors. As such, we set our base case as an int cast of the boolean number of balls leftover == 0 and number distinct colors in left == number distinct colors in right. We memoize our results and progress based on this through states of color indices, num balls leftover, num distinct left and num distinct right known as a state. \n\nThis will over count, so we need to reduce this by the number of combinations for all balls choosing half of the balls (since left and right buckets should not really have a preferencing to them). This will give us our final result correctly. \n\nTo calculate our total result before division, we need to start at color 0, with exactly half of the balls used up, and no colors in either bucket. We start with exactly half since we will need to be able to split that succesfully to zero to come to a correct answer. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTook an object oriented approach for this one. \n\nInitialize \n- balls storage \n- num colors variable \n- num balls variable \n- even split variable \n- states memo \n\nset up passing parameter of balls list \n- set balls to balls \n- set num colors to len of balls \n- sest num balls to sum of balls list \n- set even split to num balls by 2 evenly \n- set start state to [0, even split, 0, 0] representing color index 0, even split balls remaining, 0 distinct in left and 0 distinct in right\n- set start state tuple as tuple cast of above start state \n- set dividend to combination of 2 * even split and even split \n\ndp calculation passing state and state key \n- if state key in states memo -> return states memo @ state key \n- otherwise \n - if state[0] == self.num_colors \n - self.states[state_key] = int(state[1] == 0 and state[2] == state[3])\n - return self.states at state_key \n - otherwise \n - set result = 0 \n - set balls of this color to self.balls at state[0] \n - our min range will be balls of this color or num balls leftover (state[1]) + 1 \n - loop for b_i (balls of color c of count i) in range min range \n - next state is state[0] + 1, state[1] - b_i, state[2] + (b_i > 0), state[3] + (b_i < balls_here) \n - next state key is tuple of next state \n - next state value is dp of next state, next state key \n - combinations here is math.comb balls of this color, b_i\n - result is incremented by combinations * next_state value \n - self.states[state_key] = result \n - return self.states[state_key]\n\nprobability \n- return self.dp(self.start_state, self.start_state_key) / self.dividend\n\ngetProbability passing balls \n- set up passing balls \n- return probability \n\n# Complexity\n- Time complexity : O(C*B)\n - C * B : colors times num balls of that color on average \n - O(C * B) for dp progression \n - lowered by memoization progression \n - memoization also saves stack space \n\n\n- Space complexity : O(S) \n - We end up storing O(S) states \n - We do not end up exploring the entirety of O(C * B) thanks to memoization\n - This saves us from matching space complexity at the cost of O(S) states \n\n# Code\n```\nclass Solution:\n # set up with initial fields \n def __init__(self) : \n self.balls = []\n self.num_colors = 0 \n self.num_balls = 0\n self.even_split = 0 \n self.states = dict() \n\n # set up with fields initialized with values \n def set_up(self, balls) : \n self.balls = balls \n self.num_colors = len(balls)\n self.num_balls = sum(balls)\n self.even_split = self.num_balls // 2 \n self.start_state = [0, self.even_split, 0, 0]\n self.start_state_tuple = tuple(self.start_state)\n self.dividend = math.comb(2*self.even_split, self.even_split)\n \n # dp calculation \n # if you have it, return it \n # otherwise, if you are at end of color indices, return int form of all balls used and distinct on left and right match after memoizing \n # otherwise, calculate for result, using balls of this color with other components \n # return either state valuation \n def dp(self, state, state_key) : \n if state_key in self.states : \n return self.states[state_key]\n else : \n if state[0] == self.num_colors : \n self.states[state_key] = int(state[1] == 0 and state[2] == state[3])\n return self.states[state_key]\n else : \n result = 0 \n balls_of_this_color = self.balls[state[0]]\n for b_i in range(min(balls_of_this_color, state[1]) + 1) : \n # set next state up and then use to get uple form of next state key \n next_state = [state[0] + 1, state[1]-b_i, state[2]+(b_i > 0), state[3] + (b_i < balls_of_this_color)]\n next_state_key = tuple(next_state)\n # calculate next state value \n next_state_value = self.dp(next_state, next_state_key)\n # calculate combinations current \n combinations = math.comb(balls_of_this_color, b_i)\n # increment by product result \n result += combinations * next_state_value\n # set appropriately and return \n self.states[state_key] = result \n return self.states[state_key]\n\n # getter function \n def probability(self) : \n # recorded start state and start state tuple during set up, calculated divided then as well \n return self.dp(self.start_state, self.start_state_tuple) / self.dividend\n\n def getProbability(self, balls: List[int]) -> float :\n # set up and solve \n self.set_up(balls)\n return self.probability()\n``` | 0 | Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`.
All the balls will be **shuffled uniformly at random**, then we will distribute the first `n` balls to the first box and the remaining `n` balls to the other box (Please read the explanation of the second example carefully).
Please note that the two boxes are considered different. For example, if we have two balls of colors `a` and `b`, and two boxes `[]` and `()`, then the distribution `[a] (b)` is considered different than the distribution `[b] (a)` (Please read the explanation of the first example carefully).
Return _the probability_ that the two boxes have the same number of distinct balls. Answers within `10-5` of the actual value will be accepted as correct.
**Example 1:**
**Input:** balls = \[1,1\]
**Output:** 1.00000
**Explanation:** Only 2 ways to divide the balls equally:
- A ball of color 1 to box 1 and a ball of color 2 to box 2
- A ball of color 2 to box 1 and a ball of color 1 to box 2
In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1
**Example 2:**
**Input:** balls = \[2,1,1\]
**Output:** 0.66667
**Explanation:** We have the set of balls \[1, 1, 2, 3\]
This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):
\[1,1 / 2,3\], \[1,1 / 3,2\], \[1,2 / 1,3\], \[1,2 / 3,1\], \[1,3 / 1,2\], \[1,3 / 2,1\], \[2,1 / 1,3\], \[2,1 / 3,1\], \[2,3 / 1,1\], \[3,1 / 1,2\], \[3,1 / 2,1\], \[3,2 / 1,1\]
After that, we add the first two balls to the first box and the second two balls to the second box.
We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.
Probability is 8/12 = 0.66667
**Example 3:**
**Input:** balls = \[1,2,1,2\]
**Output:** 0.60000
**Explanation:** The set of balls is \[1, 2, 2, 3, 4, 4\]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.
Probability = 108 / 180 = 0.6
**Constraints:**
* `1 <= balls.length <= 8`
* `1 <= balls[i] <= 6`
* `sum(balls)` is even. | null |
Object Oriented for Memory Optimization | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can consider a dynamic programming approach concerning a valid combination. \nA valid combination is one in which all colors have been used, there are no left overs of a color, and both buckets have an equal number of distinct colors. As such, we set our base case as an int cast of the boolean number of balls leftover == 0 and number distinct colors in left == number distinct colors in right. We memoize our results and progress based on this through states of color indices, num balls leftover, num distinct left and num distinct right known as a state. \n\nThis will over count, so we need to reduce this by the number of combinations for all balls choosing half of the balls (since left and right buckets should not really have a preferencing to them). This will give us our final result correctly. \n\nTo calculate our total result before division, we need to start at color 0, with exactly half of the balls used up, and no colors in either bucket. We start with exactly half since we will need to be able to split that succesfully to zero to come to a correct answer. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTook an object oriented approach for this one. \n\nInitialize \n- balls storage \n- num colors variable \n- num balls variable \n- even split variable \n- states memo \n\nset up passing parameter of balls list \n- set balls to balls \n- set num colors to len of balls \n- sest num balls to sum of balls list \n- set even split to num balls by 2 evenly \n- set start state to [0, even split, 0, 0] representing color index 0, even split balls remaining, 0 distinct in left and 0 distinct in right\n- set start state tuple as tuple cast of above start state \n- set dividend to combination of 2 * even split and even split \n\ndp calculation passing state and state key \n- if state key in states memo -> return states memo @ state key \n- otherwise \n - if state[0] == self.num_colors \n - self.states[state_key] = int(state[1] == 0 and state[2] == state[3])\n - return self.states at state_key \n - otherwise \n - set result = 0 \n - set balls of this color to self.balls at state[0] \n - our min range will be balls of this color or num balls leftover (state[1]) + 1 \n - loop for b_i (balls of color c of count i) in range min range \n - next state is state[0] + 1, state[1] - b_i, state[2] + (b_i > 0), state[3] + (b_i < balls_here) \n - next state key is tuple of next state \n - next state value is dp of next state, next state key \n - combinations here is math.comb balls of this color, b_i\n - result is incremented by combinations * next_state value \n - self.states[state_key] = result \n - return self.states[state_key]\n\nprobability \n- return self.dp(self.start_state, self.start_state_key) / self.dividend\n\ngetProbability passing balls \n- set up passing balls \n- return probability \n\n# Complexity\n- Time complexity : O(C*B)\n - C * B : colors times num balls of that color on average \n - O(C * B) for dp progression \n - lowered by memoization progression \n - memoization also saves stack space \n\n\n- Space complexity : O(S) \n - We end up storing O(S) states \n - We do not end up exploring the entirety of O(C * B) thanks to memoization\n - This saves us from matching space complexity at the cost of O(S) states \n\n# Code\n```\nclass Solution:\n # set up with initial fields \n def __init__(self) : \n self.balls = []\n self.num_colors = 0 \n self.num_balls = 0\n self.even_split = 0 \n self.states = dict() \n\n # set up with fields initialized with values \n def set_up(self, balls) : \n self.balls = balls \n self.num_colors = len(balls)\n self.num_balls = sum(balls)\n self.even_split = self.num_balls // 2 \n self.start_state = [0, self.even_split, 0, 0]\n self.start_state_tuple = tuple(self.start_state)\n self.dividend = math.comb(2*self.even_split, self.even_split)\n \n # dp calculation \n # if you have it, return it \n # otherwise, if you are at end of color indices, return int form of all balls used and distinct on left and right match after memoizing \n # otherwise, calculate for result, using balls of this color with other components \n # return either state valuation \n def dp(self, state, state_key) : \n if state_key in self.states : \n return self.states[state_key]\n else : \n if state[0] == self.num_colors : \n self.states[state_key] = int(state[1] == 0 and state[2] == state[3])\n return self.states[state_key]\n else : \n result = 0 \n balls_of_this_color = self.balls[state[0]]\n for b_i in range(min(balls_of_this_color, state[1]) + 1) : \n # set next state up and then use to get uple form of next state key \n next_state = [state[0] + 1, state[1]-b_i, state[2]+(b_i > 0), state[3] + (b_i < balls_of_this_color)]\n next_state_key = tuple(next_state)\n # calculate next state value \n next_state_value = self.dp(next_state, next_state_key)\n # calculate combinations current \n combinations = math.comb(balls_of_this_color, b_i)\n # increment by product result \n result += combinations * next_state_value\n # set appropriately and return \n self.states[state_key] = result \n return self.states[state_key]\n\n # getter function \n def probability(self) : \n # recorded start state and start state tuple during set up, calculated divided then as well \n return self.dp(self.start_state, self.start_state_tuple) / self.dividend\n\n def getProbability(self, balls: List[int]) -> float :\n # set up and solve \n self.set_up(balls)\n return self.probability()\n``` | 0 | Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules:
* Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k < nums2.length`.
* Type 2: Triplet (i, j, k) if `nums2[i]2 == nums1[j] * nums1[k]` where `0 <= i < nums2.length` and `0 <= j < k < nums1.length`.
**Example 1:**
**Input:** nums1 = \[7,4\], nums2 = \[5,2,8,9\]
**Output:** 1
**Explanation:** Type 1: (1, 1, 2), nums1\[1\]2 = nums2\[1\] \* nums2\[2\]. (42 = 2 \* 8).
**Example 2:**
**Input:** nums1 = \[1,1\], nums2 = \[1,1,1\]
**Output:** 9
**Explanation:** All Triplets are valid, because 12 = 1 \* 1.
Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1\[i\]2 = nums2\[j\] \* nums2\[k\].
Type 2: (0,0,1), (1,0,1), (2,0,1). nums2\[i\]2 = nums1\[j\] \* nums1\[k\].
**Example 3:**
**Input:** nums1 = \[7,7,8,3\], nums2 = \[1,2,9,7\]
**Output:** 2
**Explanation:** There are 2 valid triplets.
Type 1: (3,0,2). nums1\[3\]2 = nums2\[0\] \* nums2\[2\].
Type 2: (3,0,1). nums2\[3\]2 = nums1\[0\] \* nums1\[1\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `1 <= nums1[i], nums2[i] <= 105` | Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of a draw is the sigma of probabilities of different ways to achieve draw. Can you use Dynamic programming to solve this problem in a better complexity ? |
Python3 using permutations and factorials (It is a math question) | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | 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 getProbability(self, balls: List[int]) -> float:\n fact = [1]\n for i in range(1, 49):\n fact.append(fact[-1] * i)\n \n def find_total_ways(box):\n total_balls = sum(box)\n ans = fact[total_balls]\n for count in box:\n ans //= fact[count]\n return ans\n \n def backtrack(idx, box_1, box_2):\n if idx == len(balls): \n if len(box_1) == len(box_2) and sum(box_1) == sum(box_2):\n return find_total_ways(box_1) * find_total_ways(box_2)\n else:\n return 0\n ans = 0\n\n for count1 in range(balls[idx] + 1):\n count2 = balls[idx] - count1\n if count1: box_1.append(count1)\n if count2: box_2.append(count2)\n ans += backtrack(idx + 1, box_1, box_2)\n if count1: box_1.pop()\n if count2: box_2.pop()\n \n return ans\n \n total = find_total_ways(balls)\n valid = backtrack(0, [], [])\n return valid / total\n``` | 0 | Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`.
All the balls will be **shuffled uniformly at random**, then we will distribute the first `n` balls to the first box and the remaining `n` balls to the other box (Please read the explanation of the second example carefully).
Please note that the two boxes are considered different. For example, if we have two balls of colors `a` and `b`, and two boxes `[]` and `()`, then the distribution `[a] (b)` is considered different than the distribution `[b] (a)` (Please read the explanation of the first example carefully).
Return _the probability_ that the two boxes have the same number of distinct balls. Answers within `10-5` of the actual value will be accepted as correct.
**Example 1:**
**Input:** balls = \[1,1\]
**Output:** 1.00000
**Explanation:** Only 2 ways to divide the balls equally:
- A ball of color 1 to box 1 and a ball of color 2 to box 2
- A ball of color 2 to box 1 and a ball of color 1 to box 2
In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1
**Example 2:**
**Input:** balls = \[2,1,1\]
**Output:** 0.66667
**Explanation:** We have the set of balls \[1, 1, 2, 3\]
This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):
\[1,1 / 2,3\], \[1,1 / 3,2\], \[1,2 / 1,3\], \[1,2 / 3,1\], \[1,3 / 1,2\], \[1,3 / 2,1\], \[2,1 / 1,3\], \[2,1 / 3,1\], \[2,3 / 1,1\], \[3,1 / 1,2\], \[3,1 / 2,1\], \[3,2 / 1,1\]
After that, we add the first two balls to the first box and the second two balls to the second box.
We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.
Probability is 8/12 = 0.66667
**Example 3:**
**Input:** balls = \[1,2,1,2\]
**Output:** 0.60000
**Explanation:** The set of balls is \[1, 2, 2, 3, 4, 4\]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.
Probability = 108 / 180 = 0.6
**Constraints:**
* `1 <= balls.length <= 8`
* `1 <= balls[i] <= 6`
* `sum(balls)` is even. | null |
Python3 using permutations and factorials (It is a math question) | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | 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 getProbability(self, balls: List[int]) -> float:\n fact = [1]\n for i in range(1, 49):\n fact.append(fact[-1] * i)\n \n def find_total_ways(box):\n total_balls = sum(box)\n ans = fact[total_balls]\n for count in box:\n ans //= fact[count]\n return ans\n \n def backtrack(idx, box_1, box_2):\n if idx == len(balls): \n if len(box_1) == len(box_2) and sum(box_1) == sum(box_2):\n return find_total_ways(box_1) * find_total_ways(box_2)\n else:\n return 0\n ans = 0\n\n for count1 in range(balls[idx] + 1):\n count2 = balls[idx] - count1\n if count1: box_1.append(count1)\n if count2: box_2.append(count2)\n ans += backtrack(idx + 1, box_1, box_2)\n if count1: box_1.pop()\n if count2: box_2.pop()\n \n return ans\n \n total = find_total_ways(balls)\n valid = backtrack(0, [], [])\n return valid / total\n``` | 0 | Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules:
* Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k < nums2.length`.
* Type 2: Triplet (i, j, k) if `nums2[i]2 == nums1[j] * nums1[k]` where `0 <= i < nums2.length` and `0 <= j < k < nums1.length`.
**Example 1:**
**Input:** nums1 = \[7,4\], nums2 = \[5,2,8,9\]
**Output:** 1
**Explanation:** Type 1: (1, 1, 2), nums1\[1\]2 = nums2\[1\] \* nums2\[2\]. (42 = 2 \* 8).
**Example 2:**
**Input:** nums1 = \[1,1\], nums2 = \[1,1,1\]
**Output:** 9
**Explanation:** All Triplets are valid, because 12 = 1 \* 1.
Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1\[i\]2 = nums2\[j\] \* nums2\[k\].
Type 2: (0,0,1), (1,0,1), (2,0,1). nums2\[i\]2 = nums1\[j\] \* nums1\[k\].
**Example 3:**
**Input:** nums1 = \[7,7,8,3\], nums2 = \[1,2,9,7\]
**Output:** 2
**Explanation:** There are 2 valid triplets.
Type 1: (3,0,2). nums1\[3\]2 = nums2\[0\] \* nums2\[2\].
Type 2: (3,0,1). nums2\[3\]2 = nums1\[0\] \* nums1\[1\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `1 <= nums1[i], nums2[i] <= 105` | Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of a draw is the sigma of probabilities of different ways to achieve draw. Can you use Dynamic programming to solve this problem in a better complexity ? |
python solution | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | 0 | 1 | Runtime 40ms. Beats 99.21%\n# Code\n```\nclass Solution:\n\n def C(self, n, r) -> int:\n return self.l[int(n)] / self.l[int(r)] / self.l[int(n - r)]\n \'\'\'\n params:\n idx -> what color to consider now\n first -> how many balls are filled to box 1\n second -> how many balls are filled to box 2\n disinct -> the diff of disinct color between box 1 and box 2\n return:\n the number of possible combinations\n \'\'\'\n @cache\n def helper(self, idx: int, first: int, second: int, distinct: int) -> int:\n if idx == self.size:\n return distinct == 0\n cnt = 0\n if first > self.target:\n return 0\n for i in range(0, min(self.balls[idx], self.target - first) + 1):\n base_first = self.C(self.target - first, i)\n base_second = self.C(self.target - second, self.balls[idx] - i)\n \n if i == 0:\n addition = 1\n elif i == self.balls[idx]:\n addition = -1\n else:\n addition = 0\n cnt = cnt + base_first * base_second * self.helper(idx + 1, first + i, second + self.balls[idx] - i , distinct + addition)\n \n return cnt\n\n def getProbability(self, balls: List[int]) -> float:\n a = 1\n self.l = [1]\n self.cnt = sum(balls)\n self.target = int(self.cnt / 2)\n self.size = len(balls)\n self.balls = balls\n for j in range(1, 49):\n a = a * j\n self.l.append(a)\n \n all_com = self.l[self.cnt]\n for ball in balls:\n all_com = all_com / self.l[ball]\n\n return self.helper(0, 0, 0, 0) / all_com\n``` | 0 | Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`.
All the balls will be **shuffled uniformly at random**, then we will distribute the first `n` balls to the first box and the remaining `n` balls to the other box (Please read the explanation of the second example carefully).
Please note that the two boxes are considered different. For example, if we have two balls of colors `a` and `b`, and two boxes `[]` and `()`, then the distribution `[a] (b)` is considered different than the distribution `[b] (a)` (Please read the explanation of the first example carefully).
Return _the probability_ that the two boxes have the same number of distinct balls. Answers within `10-5` of the actual value will be accepted as correct.
**Example 1:**
**Input:** balls = \[1,1\]
**Output:** 1.00000
**Explanation:** Only 2 ways to divide the balls equally:
- A ball of color 1 to box 1 and a ball of color 2 to box 2
- A ball of color 2 to box 1 and a ball of color 1 to box 2
In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1
**Example 2:**
**Input:** balls = \[2,1,1\]
**Output:** 0.66667
**Explanation:** We have the set of balls \[1, 1, 2, 3\]
This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):
\[1,1 / 2,3\], \[1,1 / 3,2\], \[1,2 / 1,3\], \[1,2 / 3,1\], \[1,3 / 1,2\], \[1,3 / 2,1\], \[2,1 / 1,3\], \[2,1 / 3,1\], \[2,3 / 1,1\], \[3,1 / 1,2\], \[3,1 / 2,1\], \[3,2 / 1,1\]
After that, we add the first two balls to the first box and the second two balls to the second box.
We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.
Probability is 8/12 = 0.66667
**Example 3:**
**Input:** balls = \[1,2,1,2\]
**Output:** 0.60000
**Explanation:** The set of balls is \[1, 2, 2, 3, 4, 4\]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.
Probability = 108 / 180 = 0.6
**Constraints:**
* `1 <= balls.length <= 8`
* `1 <= balls[i] <= 6`
* `sum(balls)` is even. | null |
python solution | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | 0 | 1 | Runtime 40ms. Beats 99.21%\n# Code\n```\nclass Solution:\n\n def C(self, n, r) -> int:\n return self.l[int(n)] / self.l[int(r)] / self.l[int(n - r)]\n \'\'\'\n params:\n idx -> what color to consider now\n first -> how many balls are filled to box 1\n second -> how many balls are filled to box 2\n disinct -> the diff of disinct color between box 1 and box 2\n return:\n the number of possible combinations\n \'\'\'\n @cache\n def helper(self, idx: int, first: int, second: int, distinct: int) -> int:\n if idx == self.size:\n return distinct == 0\n cnt = 0\n if first > self.target:\n return 0\n for i in range(0, min(self.balls[idx], self.target - first) + 1):\n base_first = self.C(self.target - first, i)\n base_second = self.C(self.target - second, self.balls[idx] - i)\n \n if i == 0:\n addition = 1\n elif i == self.balls[idx]:\n addition = -1\n else:\n addition = 0\n cnt = cnt + base_first * base_second * self.helper(idx + 1, first + i, second + self.balls[idx] - i , distinct + addition)\n \n return cnt\n\n def getProbability(self, balls: List[int]) -> float:\n a = 1\n self.l = [1]\n self.cnt = sum(balls)\n self.target = int(self.cnt / 2)\n self.size = len(balls)\n self.balls = balls\n for j in range(1, 49):\n a = a * j\n self.l.append(a)\n \n all_com = self.l[self.cnt]\n for ball in balls:\n all_com = all_com / self.l[ball]\n\n return self.helper(0, 0, 0, 0) / all_com\n``` | 0 | Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules:
* Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k < nums2.length`.
* Type 2: Triplet (i, j, k) if `nums2[i]2 == nums1[j] * nums1[k]` where `0 <= i < nums2.length` and `0 <= j < k < nums1.length`.
**Example 1:**
**Input:** nums1 = \[7,4\], nums2 = \[5,2,8,9\]
**Output:** 1
**Explanation:** Type 1: (1, 1, 2), nums1\[1\]2 = nums2\[1\] \* nums2\[2\]. (42 = 2 \* 8).
**Example 2:**
**Input:** nums1 = \[1,1\], nums2 = \[1,1,1\]
**Output:** 9
**Explanation:** All Triplets are valid, because 12 = 1 \* 1.
Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1\[i\]2 = nums2\[j\] \* nums2\[k\].
Type 2: (0,0,1), (1,0,1), (2,0,1). nums2\[i\]2 = nums1\[j\] \* nums1\[k\].
**Example 3:**
**Input:** nums1 = \[7,7,8,3\], nums2 = \[1,2,9,7\]
**Output:** 2
**Explanation:** There are 2 valid triplets.
Type 1: (3,0,2). nums1\[3\]2 = nums2\[0\] \* nums2\[2\].
Type 2: (3,0,1). nums2\[3\]2 = nums1\[0\] \* nums1\[1\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `1 <= nums1[i], nums2[i] <= 105` | Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of a draw is the sigma of probabilities of different ways to achieve draw. Can you use Dynamic programming to solve this problem in a better complexity ? |
Python Solution with Explanation | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | 1 | 1 | \tclass Solution:\n\t\tdef getProbability(self, balls: List[int]) -> float:\n\t\t\tdef solve(idx,num,k1,k2,p):\n\t\t\t\t#num is representing total number of balls in box1\n\t\t\t\t#k1 is representing the distinct balls in box1\n\t\t\t\t#k2 is representing the distinct balls in box2\n\t\t\t\t#p is representing the ways of choosing that distinct colors balls in box1 and box2\n\t\t\t\tnonlocal valids,ways,tot\n\t\t\t\tif idx==n:\n\t\t\t\t\tif num==tot:\n\t\t\t\t\t\tvalids+=(k1==k2)*p\n\t\t\t\t\t\tways+=p\n\t\t\t\t\treturn\n\t\t\t\tfor i in range(balls[idx]+1):\n\t\t\t\t\tif i+num>tot: break\n\t\t\t\t\tk11 = k1+(i>0)\n\t\t\t\t\tk22 = k2+((balls[idx]-i) > 0)\n\t\t\t\t\tsolve(idx+1,i+num,k11,k22,p*C[balls[idx]][i])\n\n\t\t\tC=[[0 for _ in range(7)] for i in range(7)]\n\t\t\tn= len(balls)\n\t\t\tfor i in range(7):\n\t\t\t\tC[i][i] = C[i][0] = 1\n\t\t\t\tfor j in range(1,i):\n\t\t\t\t\tC[i][j] = C[i-1][j-1] + C[i-1][j]\n\t\t\ttot = 0\n\t\t\tvalids = 0\n\t\t\tways = 0\n\t\t\tfor x in balls:\n\t\t\t\ttot+=x\n\t\t\ttot//=2\n\t\t\tsolve(0,0,0,0,1)\n\t\t\treturn valids/ways\n\n\n | 0 | Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`.
All the balls will be **shuffled uniformly at random**, then we will distribute the first `n` balls to the first box and the remaining `n` balls to the other box (Please read the explanation of the second example carefully).
Please note that the two boxes are considered different. For example, if we have two balls of colors `a` and `b`, and two boxes `[]` and `()`, then the distribution `[a] (b)` is considered different than the distribution `[b] (a)` (Please read the explanation of the first example carefully).
Return _the probability_ that the two boxes have the same number of distinct balls. Answers within `10-5` of the actual value will be accepted as correct.
**Example 1:**
**Input:** balls = \[1,1\]
**Output:** 1.00000
**Explanation:** Only 2 ways to divide the balls equally:
- A ball of color 1 to box 1 and a ball of color 2 to box 2
- A ball of color 2 to box 1 and a ball of color 1 to box 2
In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1
**Example 2:**
**Input:** balls = \[2,1,1\]
**Output:** 0.66667
**Explanation:** We have the set of balls \[1, 1, 2, 3\]
This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):
\[1,1 / 2,3\], \[1,1 / 3,2\], \[1,2 / 1,3\], \[1,2 / 3,1\], \[1,3 / 1,2\], \[1,3 / 2,1\], \[2,1 / 1,3\], \[2,1 / 3,1\], \[2,3 / 1,1\], \[3,1 / 1,2\], \[3,1 / 2,1\], \[3,2 / 1,1\]
After that, we add the first two balls to the first box and the second two balls to the second box.
We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.
Probability is 8/12 = 0.66667
**Example 3:**
**Input:** balls = \[1,2,1,2\]
**Output:** 0.60000
**Explanation:** The set of balls is \[1, 2, 2, 3, 4, 4\]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.
Probability = 108 / 180 = 0.6
**Constraints:**
* `1 <= balls.length <= 8`
* `1 <= balls[i] <= 6`
* `sum(balls)` is even. | null |
Python Solution with Explanation | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | 1 | 1 | \tclass Solution:\n\t\tdef getProbability(self, balls: List[int]) -> float:\n\t\t\tdef solve(idx,num,k1,k2,p):\n\t\t\t\t#num is representing total number of balls in box1\n\t\t\t\t#k1 is representing the distinct balls in box1\n\t\t\t\t#k2 is representing the distinct balls in box2\n\t\t\t\t#p is representing the ways of choosing that distinct colors balls in box1 and box2\n\t\t\t\tnonlocal valids,ways,tot\n\t\t\t\tif idx==n:\n\t\t\t\t\tif num==tot:\n\t\t\t\t\t\tvalids+=(k1==k2)*p\n\t\t\t\t\t\tways+=p\n\t\t\t\t\treturn\n\t\t\t\tfor i in range(balls[idx]+1):\n\t\t\t\t\tif i+num>tot: break\n\t\t\t\t\tk11 = k1+(i>0)\n\t\t\t\t\tk22 = k2+((balls[idx]-i) > 0)\n\t\t\t\t\tsolve(idx+1,i+num,k11,k22,p*C[balls[idx]][i])\n\n\t\t\tC=[[0 for _ in range(7)] for i in range(7)]\n\t\t\tn= len(balls)\n\t\t\tfor i in range(7):\n\t\t\t\tC[i][i] = C[i][0] = 1\n\t\t\t\tfor j in range(1,i):\n\t\t\t\t\tC[i][j] = C[i-1][j-1] + C[i-1][j]\n\t\t\ttot = 0\n\t\t\tvalids = 0\n\t\t\tways = 0\n\t\t\tfor x in balls:\n\t\t\t\ttot+=x\n\t\t\ttot//=2\n\t\t\tsolve(0,0,0,0,1)\n\t\t\treturn valids/ways\n\n\n | 0 | Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules:
* Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k < nums2.length`.
* Type 2: Triplet (i, j, k) if `nums2[i]2 == nums1[j] * nums1[k]` where `0 <= i < nums2.length` and `0 <= j < k < nums1.length`.
**Example 1:**
**Input:** nums1 = \[7,4\], nums2 = \[5,2,8,9\]
**Output:** 1
**Explanation:** Type 1: (1, 1, 2), nums1\[1\]2 = nums2\[1\] \* nums2\[2\]. (42 = 2 \* 8).
**Example 2:**
**Input:** nums1 = \[1,1\], nums2 = \[1,1,1\]
**Output:** 9
**Explanation:** All Triplets are valid, because 12 = 1 \* 1.
Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1\[i\]2 = nums2\[j\] \* nums2\[k\].
Type 2: (0,0,1), (1,0,1), (2,0,1). nums2\[i\]2 = nums1\[j\] \* nums1\[k\].
**Example 3:**
**Input:** nums1 = \[7,7,8,3\], nums2 = \[1,2,9,7\]
**Output:** 2
**Explanation:** There are 2 valid triplets.
Type 1: (3,0,2). nums1\[3\]2 = nums2\[0\] \* nums2\[2\].
Type 2: (3,0,1). nums2\[3\]2 = nums1\[0\] \* nums1\[1\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `1 <= nums1[i], nums2[i] <= 105` | Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of a draw is the sigma of probabilities of different ways to achieve draw. Can you use Dynamic programming to solve this problem in a better complexity ? |
[Python3] 52ms Solution Explained, beats 100% | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | 0 | 1 | **Big Idea: Dynamic Programming**\n\nFirst of all, let\'s propose this combination of values as a DP state:\n\n**(i, disl, disr, numl, numr)**\n\nwhere:\n**i** indicates we use up to the ith type of ball\n**disl** and **disr** are the **number of distinct types** of balls in the left and right bin\n**numl** and **numr** are the total **number of balls** in the left and right bin\n\nWhy is this dp state useful? Well, to calculate the **number of permutations** in any given dp state, say we put **j** balls in the left bin, leaving us **balls[i]-j** balls to put in the right, we only need the number of permutations at:\n\n**(i - 1, disl - ?, disr - ?, numl - j, numr - (balls[i]-j))**\n\nThe value of **?** is either 0 and 1 depending on if we are putting all the balls of ith type into one bin or not. If this is the case, then the other bin would have the same amount of distinct types, and **?** would be 0. Otherwise, the previous dp state should have one less distinct types to be relevant, so **?** would be 1.\n\nNow let\'s take a look at my solution:\n\n```\nfrom functools import lru_cache\nimport math\nclass Solution:\n def getProbability(self, balls: List[int]) -> float:\n \n @lru_cache(None)\n def fac(n):\n return math.factorial(n)\n \n @lru_cache(None)\n def dp(i, disl, disr, numl, numr):\n if i == 0: # Base case: there is only 1 valid permuatation if everything is empty\n if disl == 0 and disr == 0 and numl == 0 and numr == 0:\n return 1\n return 0\n b = balls[i-1]\n res = 0\n for j in range(b+1): # j is the number of balls we put in the left bin\n if numl - j < 0 or (numr - (b-j)) < 0: # invalid case\n continue\n ways = dp(i - 1, disl - (j != b), disr - (j != 0), numl - j, numr - (b-j))\n ways *= fac(numl) * fac(numr) / fac(j) / fac(b-j) / fac(numl-j) / fac(numr-(b-j))\n res += ways\n return res\n \n res = 0\n for k in range((len(balls) + 1) // 2, len(balls) + 1):\n res += dp(len(balls), k, k, sum(balls) // 2, sum(balls) // 2)\n \n div = fac(sum(balls))\n for b in balls:\n div //= fac(b)\n \n return res / div\n```\n\nTo understant this better, let\'s break down this solution into 4 parts:\n**Part 1** def fac(n). This is simply a short hand for computing factorials. We are memoizing it to make it faster.\n\n**Part 2** def dp(.. . This is our dynamic programming relation described above. First of all, if i = 0, then we are using no balls, so there is really only 1 way to permute it, given that the other quantities are 0 as well.\nThen, we would have to rely on the dp relation to solve this subproblem. Say we put **j** balls in the left and **b-j** balls in the right, given the number of permutations at the previous dp state, how do we solve for the number of permutations at the new state? We can approach this by first counting the total number of permutations, and then dividing by the number of ways we "overcounted". If we multiply the number of ways to permute the previous two bins without adding new balls with the total number of ways to permute the two bins after adding the new balls, then we have overcounted, for each bin: the number of ways to permute the old balls, and the number of ways to permute the new balls. The equation is given by:\n**[permutations in previous dp] * fac(numl) * fac(numr) / fac(j) / fac(b-j) / fac(numl-j) / fac(numr-(b-j))**\nNow we can proceed by summing up the number of permutations for each value of **j** we choose.\n\n**Part 3**: This where we derive the answer to the question from our dp relation. The question asks that the number of distinct types should be the same, and the number of balls in each bins are also the same. In other words, the number of balls in each bins are constantly half of the total number of balls, and we only need to enumerate the number of distinct types of balls, denoted by **k**.\n\n**Part 4**: Finally, since the question is asking about probability, not number of permutations, we divide our answer with the total number of valid permutations. In Python3, you do not need to worry about numerical overflow, so the computation process would always be valid.\n | 4 | Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`.
All the balls will be **shuffled uniformly at random**, then we will distribute the first `n` balls to the first box and the remaining `n` balls to the other box (Please read the explanation of the second example carefully).
Please note that the two boxes are considered different. For example, if we have two balls of colors `a` and `b`, and two boxes `[]` and `()`, then the distribution `[a] (b)` is considered different than the distribution `[b] (a)` (Please read the explanation of the first example carefully).
Return _the probability_ that the two boxes have the same number of distinct balls. Answers within `10-5` of the actual value will be accepted as correct.
**Example 1:**
**Input:** balls = \[1,1\]
**Output:** 1.00000
**Explanation:** Only 2 ways to divide the balls equally:
- A ball of color 1 to box 1 and a ball of color 2 to box 2
- A ball of color 2 to box 1 and a ball of color 1 to box 2
In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1
**Example 2:**
**Input:** balls = \[2,1,1\]
**Output:** 0.66667
**Explanation:** We have the set of balls \[1, 1, 2, 3\]
This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):
\[1,1 / 2,3\], \[1,1 / 3,2\], \[1,2 / 1,3\], \[1,2 / 3,1\], \[1,3 / 1,2\], \[1,3 / 2,1\], \[2,1 / 1,3\], \[2,1 / 3,1\], \[2,3 / 1,1\], \[3,1 / 1,2\], \[3,1 / 2,1\], \[3,2 / 1,1\]
After that, we add the first two balls to the first box and the second two balls to the second box.
We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.
Probability is 8/12 = 0.66667
**Example 3:**
**Input:** balls = \[1,2,1,2\]
**Output:** 0.60000
**Explanation:** The set of balls is \[1, 2, 2, 3, 4, 4\]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.
Probability = 108 / 180 = 0.6
**Constraints:**
* `1 <= balls.length <= 8`
* `1 <= balls[i] <= 6`
* `sum(balls)` is even. | null |
[Python3] 52ms Solution Explained, beats 100% | probability-of-a-two-boxes-having-the-same-number-of-distinct-balls | 0 | 1 | **Big Idea: Dynamic Programming**\n\nFirst of all, let\'s propose this combination of values as a DP state:\n\n**(i, disl, disr, numl, numr)**\n\nwhere:\n**i** indicates we use up to the ith type of ball\n**disl** and **disr** are the **number of distinct types** of balls in the left and right bin\n**numl** and **numr** are the total **number of balls** in the left and right bin\n\nWhy is this dp state useful? Well, to calculate the **number of permutations** in any given dp state, say we put **j** balls in the left bin, leaving us **balls[i]-j** balls to put in the right, we only need the number of permutations at:\n\n**(i - 1, disl - ?, disr - ?, numl - j, numr - (balls[i]-j))**\n\nThe value of **?** is either 0 and 1 depending on if we are putting all the balls of ith type into one bin or not. If this is the case, then the other bin would have the same amount of distinct types, and **?** would be 0. Otherwise, the previous dp state should have one less distinct types to be relevant, so **?** would be 1.\n\nNow let\'s take a look at my solution:\n\n```\nfrom functools import lru_cache\nimport math\nclass Solution:\n def getProbability(self, balls: List[int]) -> float:\n \n @lru_cache(None)\n def fac(n):\n return math.factorial(n)\n \n @lru_cache(None)\n def dp(i, disl, disr, numl, numr):\n if i == 0: # Base case: there is only 1 valid permuatation if everything is empty\n if disl == 0 and disr == 0 and numl == 0 and numr == 0:\n return 1\n return 0\n b = balls[i-1]\n res = 0\n for j in range(b+1): # j is the number of balls we put in the left bin\n if numl - j < 0 or (numr - (b-j)) < 0: # invalid case\n continue\n ways = dp(i - 1, disl - (j != b), disr - (j != 0), numl - j, numr - (b-j))\n ways *= fac(numl) * fac(numr) / fac(j) / fac(b-j) / fac(numl-j) / fac(numr-(b-j))\n res += ways\n return res\n \n res = 0\n for k in range((len(balls) + 1) // 2, len(balls) + 1):\n res += dp(len(balls), k, k, sum(balls) // 2, sum(balls) // 2)\n \n div = fac(sum(balls))\n for b in balls:\n div //= fac(b)\n \n return res / div\n```\n\nTo understant this better, let\'s break down this solution into 4 parts:\n**Part 1** def fac(n). This is simply a short hand for computing factorials. We are memoizing it to make it faster.\n\n**Part 2** def dp(.. . This is our dynamic programming relation described above. First of all, if i = 0, then we are using no balls, so there is really only 1 way to permute it, given that the other quantities are 0 as well.\nThen, we would have to rely on the dp relation to solve this subproblem. Say we put **j** balls in the left and **b-j** balls in the right, given the number of permutations at the previous dp state, how do we solve for the number of permutations at the new state? We can approach this by first counting the total number of permutations, and then dividing by the number of ways we "overcounted". If we multiply the number of ways to permute the previous two bins without adding new balls with the total number of ways to permute the two bins after adding the new balls, then we have overcounted, for each bin: the number of ways to permute the old balls, and the number of ways to permute the new balls. The equation is given by:\n**[permutations in previous dp] * fac(numl) * fac(numr) / fac(j) / fac(b-j) / fac(numl-j) / fac(numr-(b-j))**\nNow we can proceed by summing up the number of permutations for each value of **j** we choose.\n\n**Part 3**: This where we derive the answer to the question from our dp relation. The question asks that the number of distinct types should be the same, and the number of balls in each bins are also the same. In other words, the number of balls in each bins are constantly half of the total number of balls, and we only need to enumerate the number of distinct types of balls, denoted by **k**.\n\n**Part 4**: Finally, since the question is asking about probability, not number of permutations, we divide our answer with the total number of valid permutations. In Python3, you do not need to worry about numerical overflow, so the computation process would always be valid.\n | 4 | Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules:
* Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k < nums2.length`.
* Type 2: Triplet (i, j, k) if `nums2[i]2 == nums1[j] * nums1[k]` where `0 <= i < nums2.length` and `0 <= j < k < nums1.length`.
**Example 1:**
**Input:** nums1 = \[7,4\], nums2 = \[5,2,8,9\]
**Output:** 1
**Explanation:** Type 1: (1, 1, 2), nums1\[1\]2 = nums2\[1\] \* nums2\[2\]. (42 = 2 \* 8).
**Example 2:**
**Input:** nums1 = \[1,1\], nums2 = \[1,1,1\]
**Output:** 9
**Explanation:** All Triplets are valid, because 12 = 1 \* 1.
Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1\[i\]2 = nums2\[j\] \* nums2\[k\].
Type 2: (0,0,1), (1,0,1), (2,0,1). nums2\[i\]2 = nums1\[j\] \* nums1\[k\].
**Example 3:**
**Input:** nums1 = \[7,7,8,3\], nums2 = \[1,2,9,7\]
**Output:** 2
**Explanation:** There are 2 valid triplets.
Type 1: (3,0,2). nums1\[3\]2 = nums2\[0\] \* nums2\[2\].
Type 2: (3,0,1). nums2\[3\]2 = nums1\[0\] \* nums1\[1\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `1 <= nums1[i], nums2[i] <= 105` | Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of a draw is the sigma of probabilities of different ways to achieve draw. Can you use Dynamic programming to solve this problem in a better complexity ? |
Solutions in C++ and Python👊Learn and Master Arrays in Programming(^_+) | shuffle-the-array | 0 | 1 | # Solution in C++\n```\nclass Solution {\npublic:\n vector<int> shuffle(vector<int>& nums, int n) {\n vector<int>result;\n for (int i = 0; i < nums.size() / 2; i++){\n result.push_back(nums.at(i));\n result.push_back(nums.at(i+n));\n }\n return result;\n }\n};\n```\n# Solution in Python\n```\nclass Solution:\n def shuffle(self, nums: List[int], n: int) -> List[int]:\n array1 = nums[:n]\n array2 = nums[n:]\n result = []\n for i in range(len(array1)):\n result.append(array1[i])\n result.append(array2[i])\n\n return result\n``` | 2 | Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`.
_Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`.
**Example 1:**
**Input:** nums = \[2,5,1,3,4,7\], n = 3
**Output:** \[2,3,5,4,1,7\]
**Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer is \[2,3,5,4,1,7\].
**Example 2:**
**Input:** nums = \[1,2,3,4,4,3,2,1\], n = 4
**Output:** \[1,4,2,3,3,2,4,1\]
**Example 3:**
**Input:** nums = \[1,1,2,2\], n = 2
**Output:** \[1,2,1,2\]
**Constraints:**
* `1 <= n <= 500`
* `nums.length == 2n`
* `1 <= nums[i] <= 10^3` | null |
Beats 86.91% | Shuffle the array | shuffle-the-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def shuffle(self, nums: List[int], n: int) -> List[int]:\n arr1=[]\n arr2=[]\n arr3=[]\n for i in range(n):\n arr1.append(nums[i])\n for i in range(n,2*n):\n arr2.append(nums[i])\n for i in range(n):\n arr3.append(arr1[i])\n arr3.append(arr2[i])\n return arr3\n``` | 1 | Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`.
_Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`.
**Example 1:**
**Input:** nums = \[2,5,1,3,4,7\], n = 3
**Output:** \[2,3,5,4,1,7\]
**Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer is \[2,3,5,4,1,7\].
**Example 2:**
**Input:** nums = \[1,2,3,4,4,3,2,1\], n = 4
**Output:** \[1,4,2,3,3,2,4,1\]
**Example 3:**
**Input:** nums = \[1,1,2,2\], n = 2
**Output:** \[1,2,1,2\]
**Constraints:**
* `1 <= n <= 500`
* `nums.length == 2n`
* `1 <= nums[i] <= 10^3` | null |
Simple python3 solution, have a nice day. | shuffle-the-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def shuffle(self, nums: List[int], n: int) -> List[int]:\n new = []\n half_index = len(nums) // 2\n for i in range(len(nums) // 2):\n new.append(nums[i])\n new.append(nums[i + half_index])\n return new\n \n``` | 1 | Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`.
_Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`.
**Example 1:**
**Input:** nums = \[2,5,1,3,4,7\], n = 3
**Output:** \[2,3,5,4,1,7\]
**Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer is \[2,3,5,4,1,7\].
**Example 2:**
**Input:** nums = \[1,2,3,4,4,3,2,1\], n = 4
**Output:** \[1,4,2,3,3,2,4,1\]
**Example 3:**
**Input:** nums = \[1,1,2,2\], n = 2
**Output:** \[1,2,1,2\]
**Constraints:**
* `1 <= n <= 500`
* `nums.length == 2n`
* `1 <= nums[i] <= 10^3` | null |
Rust and Python O(n) space. 100% faster in Rust. | shuffle-the-array | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n\nSimple map/List comprehension iteration over the given vetor/List.\nIt\'s really efficient, it seems for Rust.\n\n\n\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(n)\n\n# Code\nRust:\n```\nimpl Solution {\n pub fn shuffle(nums: Vec<i32>, n: i32) -> Vec<i32> {\n (0..nums.len()).map(|x| nums[x/2 + (x%2)*nums.len()/2 ]).collect::<Vec<_>>()\n }\n}\n```\nPython3:\n```\nclass Solution:\n def shuffle(self, nums: List[int], n: int) -> List[int]:\n return [nums[i+(j%2)*(len(nums)//2)] for i in range(len(nums)//2) for j in range(2) ]\n``` | 2 | Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`.
_Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`.
**Example 1:**
**Input:** nums = \[2,5,1,3,4,7\], n = 3
**Output:** \[2,3,5,4,1,7\]
**Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer is \[2,3,5,4,1,7\].
**Example 2:**
**Input:** nums = \[1,2,3,4,4,3,2,1\], n = 4
**Output:** \[1,4,2,3,3,2,4,1\]
**Example 3:**
**Input:** nums = \[1,1,2,2\], n = 2
**Output:** \[1,2,1,2\]
**Constraints:**
* `1 <= n <= 500`
* `nums.length == 2n`
* `1 <= nums[i] <= 10^3` | null |
python3 two pointer | the-k-strongest-values-in-an-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n O(NlogN)\n\n- Space complexity:\n O(N)\n# Code\n```\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n mid = arr[(len(arr)-1)//2]\n ans = []\n l ,r = 0, len(arr)-1\n while(l <= r):\n if abs(arr[l] - mid) > abs(arr[r]-mid) :\n ans.append(arr[l])\n l+=1\n else:\n ans.append(arr[r])\n r-=1\n return ans[:k]\n``` | 1 | Given an array of integers `arr` and an integer `k`.
A value `arr[i]` is said to be stronger than a value `arr[j]` if `|arr[i] - m| > |arr[j] - m|` where `m` is the **median** of the array.
If `|arr[i] - m| == |arr[j] - m|`, then `arr[i]` is said to be stronger than `arr[j]` if `arr[i] > arr[j]`.
Return _a list of the strongest `k`_ values in the array. return the answer **in any arbitrary order**.
**Median** is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position `((n - 1) / 2)` in the sorted list **(0-indexed)**.
* For `arr = [6, -3, 7, 2, 11]`, `n = 5` and the median is obtained by sorting the array `arr = [-3, 2, 6, 7, 11]` and the median is `arr[m]` where `m = ((5 - 1) / 2) = 2`. The median is `6`.
* For `arr = [-7, 22, 17, 3]`, `n = 4` and the median is obtained by sorting the array `arr = [-7, 3, 17, 22]` and the median is `arr[m]` where `m = ((4 - 1) / 2) = 1`. The median is `3`.
**Example 1:**
**Input:** arr = \[1,2,3,4,5\], k = 2
**Output:** \[5,1\]
**Explanation:** Median is 3, the elements of the array sorted by the strongest are \[5,1,4,2,3\]. The strongest 2 elements are \[5, 1\]. \[1, 5\] is also **accepted** answer.
Please note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.
**Example 2:**
**Input:** arr = \[1,1,3,5,5\], k = 2
**Output:** \[5,5\]
**Explanation:** Median is 3, the elements of the array sorted by the strongest are \[5,5,1,1,3\]. The strongest 2 elements are \[5, 5\].
**Example 3:**
**Input:** arr = \[6,7,11,7,6,8\], k = 5
**Output:** \[11,8,6,6,7\]
**Explanation:** Median is 7, the elements of the array sorted by the strongest are \[11,8,6,6,7,7\].
Any permutation of \[11,8,6,6,7\] is **accepted**.
**Constraints:**
* `1 <= arr.length <= 105`
* `-105 <= arr[i] <= 105`
* `1 <= k <= arr.length` | Students in row i only can see exams in row i+1. Use Dynamic programming to compute the result given a (current row, bitmask people seated in previous row). |
[Python3] straightforward 2 lines with custom sort | the-k-strongest-values-in-an-array | 0 | 1 | 1. get median by sorting and getting the `(n-1)/2` th element\n2. use lambda to do custom sort. since we need maximum, take negative of difference. if difference is equal, we just get the larger value element\n\n```\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n m = sorted(arr)[(len(arr) - 1) // 2]\n return sorted(arr, key = lambda x: (-abs(x - m), -x))[:k]\n```\n\nSuggestion by @Gausstotle that makes sorting even easier to understand:\n\n```\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n m = sorted(arr)[(len(arr) - 1) // 2]\n return sorted(arr, reverse=True, key = lambda x: (abs(x - m), x))[:k]\n```\n | 16 | Given an array of integers `arr` and an integer `k`.
A value `arr[i]` is said to be stronger than a value `arr[j]` if `|arr[i] - m| > |arr[j] - m|` where `m` is the **median** of the array.
If `|arr[i] - m| == |arr[j] - m|`, then `arr[i]` is said to be stronger than `arr[j]` if `arr[i] > arr[j]`.
Return _a list of the strongest `k`_ values in the array. return the answer **in any arbitrary order**.
**Median** is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position `((n - 1) / 2)` in the sorted list **(0-indexed)**.
* For `arr = [6, -3, 7, 2, 11]`, `n = 5` and the median is obtained by sorting the array `arr = [-3, 2, 6, 7, 11]` and the median is `arr[m]` where `m = ((5 - 1) / 2) = 2`. The median is `6`.
* For `arr = [-7, 22, 17, 3]`, `n = 4` and the median is obtained by sorting the array `arr = [-7, 3, 17, 22]` and the median is `arr[m]` where `m = ((4 - 1) / 2) = 1`. The median is `3`.
**Example 1:**
**Input:** arr = \[1,2,3,4,5\], k = 2
**Output:** \[5,1\]
**Explanation:** Median is 3, the elements of the array sorted by the strongest are \[5,1,4,2,3\]. The strongest 2 elements are \[5, 1\]. \[1, 5\] is also **accepted** answer.
Please note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.
**Example 2:**
**Input:** arr = \[1,1,3,5,5\], k = 2
**Output:** \[5,5\]
**Explanation:** Median is 3, the elements of the array sorted by the strongest are \[5,5,1,1,3\]. The strongest 2 elements are \[5, 5\].
**Example 3:**
**Input:** arr = \[6,7,11,7,6,8\], k = 5
**Output:** \[11,8,6,6,7\]
**Explanation:** Median is 7, the elements of the array sorted by the strongest are \[11,8,6,6,7,7\].
Any permutation of \[11,8,6,6,7\] is **accepted**.
**Constraints:**
* `1 <= arr.length <= 105`
* `-105 <= arr[i] <= 105`
* `1 <= k <= arr.length` | Students in row i only can see exams in row i+1. Use Dynamic programming to compute the result given a (current row, bitmask people seated in previous row). |
Python solution (2 lines) 100% faster runtime | the-k-strongest-values-in-an-array | 0 | 1 | \n```\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n med = sorted(arr[(len(arr)-1)//2])\n \xA0 \xA0 \xA0 \xA0return sorted(array, key=lambda x:(abs(x-med),x))[-k:]\n``` | 8 | Given an array of integers `arr` and an integer `k`.
A value `arr[i]` is said to be stronger than a value `arr[j]` if `|arr[i] - m| > |arr[j] - m|` where `m` is the **median** of the array.
If `|arr[i] - m| == |arr[j] - m|`, then `arr[i]` is said to be stronger than `arr[j]` if `arr[i] > arr[j]`.
Return _a list of the strongest `k`_ values in the array. return the answer **in any arbitrary order**.
**Median** is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position `((n - 1) / 2)` in the sorted list **(0-indexed)**.
* For `arr = [6, -3, 7, 2, 11]`, `n = 5` and the median is obtained by sorting the array `arr = [-3, 2, 6, 7, 11]` and the median is `arr[m]` where `m = ((5 - 1) / 2) = 2`. The median is `6`.
* For `arr = [-7, 22, 17, 3]`, `n = 4` and the median is obtained by sorting the array `arr = [-7, 3, 17, 22]` and the median is `arr[m]` where `m = ((4 - 1) / 2) = 1`. The median is `3`.
**Example 1:**
**Input:** arr = \[1,2,3,4,5\], k = 2
**Output:** \[5,1\]
**Explanation:** Median is 3, the elements of the array sorted by the strongest are \[5,1,4,2,3\]. The strongest 2 elements are \[5, 1\]. \[1, 5\] is also **accepted** answer.
Please note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.
**Example 2:**
**Input:** arr = \[1,1,3,5,5\], k = 2
**Output:** \[5,5\]
**Explanation:** Median is 3, the elements of the array sorted by the strongest are \[5,5,1,1,3\]. The strongest 2 elements are \[5, 5\].
**Example 3:**
**Input:** arr = \[6,7,11,7,6,8\], k = 5
**Output:** \[11,8,6,6,7\]
**Explanation:** Median is 7, the elements of the array sorted by the strongest are \[11,8,6,6,7,7\].
Any permutation of \[11,8,6,6,7\] is **accepted**.
**Constraints:**
* `1 <= arr.length <= 105`
* `-105 <= arr[i] <= 105`
* `1 <= k <= arr.length` | Students in row i only can see exams in row i+1. Use Dynamic programming to compute the result given a (current row, bitmask people seated in previous row). |
Easy python solution🐍🔥 | design-browser-history | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(1), O(1), O(n), O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1), O(1), O(1), O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass ListNode:\n def __init__(self, val, prev=None, next= None):\n self.val = val\n self.prev = prev\n self.next = next\n\nclass BrowserHistory:\n\n def __init__(self, homepage: str):\n self.cur = ListNode(homepage)\n\n def visit(self, url: str) -> None:\n self.cur.next = ListNode(url, self.cur)\n self.cur = self.cur.next\n\n def back(self, steps: int) -> str:\n while self.cur.prev and steps > 0:\n self.cur = self.cur.prev\n steps -= 1\n return self.cur.val\n\n def forward(self, steps: int) -> str:\n while self.cur.next and steps > 0:\n self.cur = self.cur.next\n steps -= 1\n return self.cur.val\n \n\n\n# Your BrowserHistory object will be instantiated and called as such:\n# obj = BrowserHistory(homepage)\n# obj.visit(url)\n# param_2 = obj.back(steps)\n# param_3 = obj.forward(steps)\n``` | 1 | You have a **browser** of one tab where you start on the `homepage` and you can visit another `url`, get back in the history number of `steps` or move forward in the history number of `steps`.
Implement the `BrowserHistory` class:
* `BrowserHistory(string homepage)` Initializes the object with the `homepage` of the browser.
* `void visit(string url)` Visits `url` from the current page. It clears up all the forward history.
* `string back(int steps)` Move `steps` back in history. If you can only return `x` steps in the history and `steps > x`, you will return only `x` steps. Return the current `url` after moving back in history **at most** `steps`.
* `string forward(int steps)` Move `steps` forward in history. If you can only forward `x` steps in the history and `steps > x`, you will forward only `x` steps. Return the current `url` after forwarding in history **at most** `steps`.
**Example:**
**Input:**
\[ "BrowserHistory ", "visit ", "visit ", "visit ", "back ", "back ", "forward ", "visit ", "forward ", "back ", "back "\]
\[\[ "leetcode.com "\],\[ "google.com "\],\[ "facebook.com "\],\[ "youtube.com "\],\[1\],\[1\],\[1\],\[ "linkedin.com "\],\[2\],\[2\],\[7\]\]
**Output:**
\[null,null,null,null, "facebook.com ", "google.com ", "facebook.com ",null, "linkedin.com ", "google.com ", "leetcode.com "\]
**Explanation:**
BrowserHistory browserHistory = new BrowserHistory( "leetcode.com ");
browserHistory.visit( "google.com "); // You are in "leetcode.com ". Visit "google.com "
browserHistory.visit( "facebook.com "); // You are in "google.com ". Visit "facebook.com "
browserHistory.visit( "youtube.com "); // You are in "facebook.com ". Visit "youtube.com "
browserHistory.back(1); // You are in "youtube.com ", move back to "facebook.com " return "facebook.com "
browserHistory.back(1); // You are in "facebook.com ", move back to "google.com " return "google.com "
browserHistory.forward(1); // You are in "google.com ", move forward to "facebook.com " return "facebook.com "
browserHistory.visit( "linkedin.com "); // You are in "facebook.com ". Visit "linkedin.com "
browserHistory.forward(2); // You are in "linkedin.com ", you cannot move forward any steps.
browserHistory.back(2); // You are in "linkedin.com ", move back two steps to "facebook.com " then to "google.com ". return "google.com "
browserHistory.back(7); // You are in "google.com ", you can move back only one step to "leetcode.com ". return "leetcode.com "
**Constraints:**
* `1 <= homepage.length <= 20`
* `1 <= url.length <= 20`
* `1 <= steps <= 100`
* `homepage` and `url` consist of '.' or lower case English letters.
* At most `5000` calls will be made to `visit`, `back`, and `forward`. | Count the frequency of each character. Loop over all character from 'a' to 'z' and append the character if it exists and decrease frequency by 1. Do the same from 'z' to 'a'. Keep repeating until the frequency of all characters is zero. |
Easy python solution🐍🔥 | design-browser-history | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(1), O(1), O(n), O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1), O(1), O(1), O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass ListNode:\n def __init__(self, val, prev=None, next= None):\n self.val = val\n self.prev = prev\n self.next = next\n\nclass BrowserHistory:\n\n def __init__(self, homepage: str):\n self.cur = ListNode(homepage)\n\n def visit(self, url: str) -> None:\n self.cur.next = ListNode(url, self.cur)\n self.cur = self.cur.next\n\n def back(self, steps: int) -> str:\n while self.cur.prev and steps > 0:\n self.cur = self.cur.prev\n steps -= 1\n return self.cur.val\n\n def forward(self, steps: int) -> str:\n while self.cur.next and steps > 0:\n self.cur = self.cur.next\n steps -= 1\n return self.cur.val\n \n\n\n# Your BrowserHistory object will be instantiated and called as such:\n# obj = BrowserHistory(homepage)\n# obj.visit(url)\n# param_2 = obj.back(steps)\n# param_3 = obj.forward(steps)\n``` | 1 | Given an `m x n` binary matrix `mat`, return _the number of special positions in_ `mat`_._
A position `(i, j)` is called **special** if `mat[i][j] == 1` and all other elements in row `i` and column `j` are `0` (rows and columns are **0-indexed**).
**Example 1:**
**Input:** mat = \[\[1,0,0\],\[0,0,1\],\[1,0,0\]\]
**Output:** 1
**Explanation:** (1, 2) is a special position because mat\[1\]\[2\] == 1 and all other elements in row 1 and column 2 are 0.
**Example 2:**
**Input:** mat = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\]
**Output:** 3
**Explanation:** (0, 0), (1, 1) and (2, 2) are special positions.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 100`
* `mat[i][j]` is either `0` or `1`. | Use two stack one for back history and one for forward history and simulate the functions. Can you do faster by using different data structure ? |
Dynamic Array | Explained | O(1) each operation | C++ | Python | design-browser-history | 0 | 1 | \n<iframe src="https://leetcode.com/playground/EAaTWi42/shared" frameBorder="0" width="1000" height="800"></iframe>\n\nIf you feel it useful please upvote \uD83D\uDE0A\uD83D\uDE0A.\nIn case of any queries or suggestions please let me know in the comment section. | 1 | You have a **browser** of one tab where you start on the `homepage` and you can visit another `url`, get back in the history number of `steps` or move forward in the history number of `steps`.
Implement the `BrowserHistory` class:
* `BrowserHistory(string homepage)` Initializes the object with the `homepage` of the browser.
* `void visit(string url)` Visits `url` from the current page. It clears up all the forward history.
* `string back(int steps)` Move `steps` back in history. If you can only return `x` steps in the history and `steps > x`, you will return only `x` steps. Return the current `url` after moving back in history **at most** `steps`.
* `string forward(int steps)` Move `steps` forward in history. If you can only forward `x` steps in the history and `steps > x`, you will forward only `x` steps. Return the current `url` after forwarding in history **at most** `steps`.
**Example:**
**Input:**
\[ "BrowserHistory ", "visit ", "visit ", "visit ", "back ", "back ", "forward ", "visit ", "forward ", "back ", "back "\]
\[\[ "leetcode.com "\],\[ "google.com "\],\[ "facebook.com "\],\[ "youtube.com "\],\[1\],\[1\],\[1\],\[ "linkedin.com "\],\[2\],\[2\],\[7\]\]
**Output:**
\[null,null,null,null, "facebook.com ", "google.com ", "facebook.com ",null, "linkedin.com ", "google.com ", "leetcode.com "\]
**Explanation:**
BrowserHistory browserHistory = new BrowserHistory( "leetcode.com ");
browserHistory.visit( "google.com "); // You are in "leetcode.com ". Visit "google.com "
browserHistory.visit( "facebook.com "); // You are in "google.com ". Visit "facebook.com "
browserHistory.visit( "youtube.com "); // You are in "facebook.com ". Visit "youtube.com "
browserHistory.back(1); // You are in "youtube.com ", move back to "facebook.com " return "facebook.com "
browserHistory.back(1); // You are in "facebook.com ", move back to "google.com " return "google.com "
browserHistory.forward(1); // You are in "google.com ", move forward to "facebook.com " return "facebook.com "
browserHistory.visit( "linkedin.com "); // You are in "facebook.com ". Visit "linkedin.com "
browserHistory.forward(2); // You are in "linkedin.com ", you cannot move forward any steps.
browserHistory.back(2); // You are in "linkedin.com ", move back two steps to "facebook.com " then to "google.com ". return "google.com "
browserHistory.back(7); // You are in "google.com ", you can move back only one step to "leetcode.com ". return "leetcode.com "
**Constraints:**
* `1 <= homepage.length <= 20`
* `1 <= url.length <= 20`
* `1 <= steps <= 100`
* `homepage` and `url` consist of '.' or lower case English letters.
* At most `5000` calls will be made to `visit`, `back`, and `forward`. | Count the frequency of each character. Loop over all character from 'a' to 'z' and append the character if it exists and decrease frequency by 1. Do the same from 'z' to 'a'. Keep repeating until the frequency of all characters is zero. |
Dynamic Array | Explained | O(1) each operation | C++ | Python | design-browser-history | 0 | 1 | \n<iframe src="https://leetcode.com/playground/EAaTWi42/shared" frameBorder="0" width="1000" height="800"></iframe>\n\nIf you feel it useful please upvote \uD83D\uDE0A\uD83D\uDE0A.\nIn case of any queries or suggestions please let me know in the comment section. | 1 | Given an `m x n` binary matrix `mat`, return _the number of special positions in_ `mat`_._
A position `(i, j)` is called **special** if `mat[i][j] == 1` and all other elements in row `i` and column `j` are `0` (rows and columns are **0-indexed**).
**Example 1:**
**Input:** mat = \[\[1,0,0\],\[0,0,1\],\[1,0,0\]\]
**Output:** 1
**Explanation:** (1, 2) is a special position because mat\[1\]\[2\] == 1 and all other elements in row 1 and column 2 are 0.
**Example 2:**
**Input:** mat = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\]
**Output:** 3
**Explanation:** (0, 0), (1, 1) and (2, 2) are special positions.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 100`
* `mat[i][j]` is either `0` or `1`. | Use two stack one for back history and one for forward history and simulate the functions. Can you do faster by using different data structure ? |
python3 Solution | design-browser-history | 0 | 1 | \n```\nclass BrowserHistory:\n\n def __init__(self, homepage: str):\n self.stack=[homepage]\n self.pointer=0\n\n def visit(self, url: str) -> None:\n self.stack=self.stack[:self.pointer+1]\n self.stack.append(url)\n self.pointer=len(self.stack)-1\n\n def back(self, steps: int) -> str:\n self.pointer=max(self.pointer-steps,0)\n return self.stack[self.pointer]\n\n def forward(self, steps: int) -> str:\n self.pointer=min(self.pointer+steps,len(self.stack)-1)\n return self.stack[self.pointer]\n\n\n# Your BrowserHistory object will be instantiated and called as such:\n# obj = BrowserHistory(homepage)\n# obj.visit(url)\n# param_2 = obj.back(steps)\n# param_3 = obj.forward(steps)\n``` | 1 | You have a **browser** of one tab where you start on the `homepage` and you can visit another `url`, get back in the history number of `steps` or move forward in the history number of `steps`.
Implement the `BrowserHistory` class:
* `BrowserHistory(string homepage)` Initializes the object with the `homepage` of the browser.
* `void visit(string url)` Visits `url` from the current page. It clears up all the forward history.
* `string back(int steps)` Move `steps` back in history. If you can only return `x` steps in the history and `steps > x`, you will return only `x` steps. Return the current `url` after moving back in history **at most** `steps`.
* `string forward(int steps)` Move `steps` forward in history. If you can only forward `x` steps in the history and `steps > x`, you will forward only `x` steps. Return the current `url` after forwarding in history **at most** `steps`.
**Example:**
**Input:**
\[ "BrowserHistory ", "visit ", "visit ", "visit ", "back ", "back ", "forward ", "visit ", "forward ", "back ", "back "\]
\[\[ "leetcode.com "\],\[ "google.com "\],\[ "facebook.com "\],\[ "youtube.com "\],\[1\],\[1\],\[1\],\[ "linkedin.com "\],\[2\],\[2\],\[7\]\]
**Output:**
\[null,null,null,null, "facebook.com ", "google.com ", "facebook.com ",null, "linkedin.com ", "google.com ", "leetcode.com "\]
**Explanation:**
BrowserHistory browserHistory = new BrowserHistory( "leetcode.com ");
browserHistory.visit( "google.com "); // You are in "leetcode.com ". Visit "google.com "
browserHistory.visit( "facebook.com "); // You are in "google.com ". Visit "facebook.com "
browserHistory.visit( "youtube.com "); // You are in "facebook.com ". Visit "youtube.com "
browserHistory.back(1); // You are in "youtube.com ", move back to "facebook.com " return "facebook.com "
browserHistory.back(1); // You are in "facebook.com ", move back to "google.com " return "google.com "
browserHistory.forward(1); // You are in "google.com ", move forward to "facebook.com " return "facebook.com "
browserHistory.visit( "linkedin.com "); // You are in "facebook.com ". Visit "linkedin.com "
browserHistory.forward(2); // You are in "linkedin.com ", you cannot move forward any steps.
browserHistory.back(2); // You are in "linkedin.com ", move back two steps to "facebook.com " then to "google.com ". return "google.com "
browserHistory.back(7); // You are in "google.com ", you can move back only one step to "leetcode.com ". return "leetcode.com "
**Constraints:**
* `1 <= homepage.length <= 20`
* `1 <= url.length <= 20`
* `1 <= steps <= 100`
* `homepage` and `url` consist of '.' or lower case English letters.
* At most `5000` calls will be made to `visit`, `back`, and `forward`. | Count the frequency of each character. Loop over all character from 'a' to 'z' and append the character if it exists and decrease frequency by 1. Do the same from 'z' to 'a'. Keep repeating until the frequency of all characters is zero. |
python3 Solution | design-browser-history | 0 | 1 | \n```\nclass BrowserHistory:\n\n def __init__(self, homepage: str):\n self.stack=[homepage]\n self.pointer=0\n\n def visit(self, url: str) -> None:\n self.stack=self.stack[:self.pointer+1]\n self.stack.append(url)\n self.pointer=len(self.stack)-1\n\n def back(self, steps: int) -> str:\n self.pointer=max(self.pointer-steps,0)\n return self.stack[self.pointer]\n\n def forward(self, steps: int) -> str:\n self.pointer=min(self.pointer+steps,len(self.stack)-1)\n return self.stack[self.pointer]\n\n\n# Your BrowserHistory object will be instantiated and called as such:\n# obj = BrowserHistory(homepage)\n# obj.visit(url)\n# param_2 = obj.back(steps)\n# param_3 = obj.forward(steps)\n``` | 1 | Given an `m x n` binary matrix `mat`, return _the number of special positions in_ `mat`_._
A position `(i, j)` is called **special** if `mat[i][j] == 1` and all other elements in row `i` and column `j` are `0` (rows and columns are **0-indexed**).
**Example 1:**
**Input:** mat = \[\[1,0,0\],\[0,0,1\],\[1,0,0\]\]
**Output:** 1
**Explanation:** (1, 2) is a special position because mat\[1\]\[2\] == 1 and all other elements in row 1 and column 2 are 0.
**Example 2:**
**Input:** mat = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\]
**Output:** 3
**Explanation:** (0, 0), (1, 1) and (2, 2) are special positions.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 100`
* `mat[i][j]` is either `0` or `1`. | Use two stack one for back history and one for forward history and simulate the functions. Can you do faster by using different data structure ? |
Python short and clean. DoublyLinkedList. | design-browser-history | 0 | 1 | # Approach\nTL;DR, Same as [Official LinkedList solution](https://leetcode.com/problems/design-browser-history/editorial/)\n\n# Complexity\n`__init__` and `visit` functions:\n- Time complexity: $$O(1)$$\n\n- Space complexity: $$O(1)$$\n\n`back` and `forward` functions:\n- Time complexity: $$O(k)$$, where `k is number of steps`.\n\n- Space complexity: $$O(1)$$\n\n`n` calls to `visit` function:\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```python\nfrom dataclasses import dataclass\n\nclass BrowserHistory:\n\n def __init__(self, homepage: str):\n self.page = DLLNode(homepage)\n\n def visit(self, url: str) -> None:\n a, b = self.page, DLLNode(url)\n a.next, b.prev = b, a\n self.page = b\n\n def back(self, steps: int) -> str:\n while self.page.prev and steps: self.page = self.page.prev; steps -= 1\n return self.page.value\n\n def forward(self, steps: int) -> str:\n while self.page.next and steps: self.page = self.page.next; steps -= 1\n return self.page.value\n\n@dataclass\nclass DLLNode:\n value: Any = None\n prev: \'DLLNode | None\' = None\n next: \'DLLNode | None\' = None\n\n\n``` | 2 | You have a **browser** of one tab where you start on the `homepage` and you can visit another `url`, get back in the history number of `steps` or move forward in the history number of `steps`.
Implement the `BrowserHistory` class:
* `BrowserHistory(string homepage)` Initializes the object with the `homepage` of the browser.
* `void visit(string url)` Visits `url` from the current page. It clears up all the forward history.
* `string back(int steps)` Move `steps` back in history. If you can only return `x` steps in the history and `steps > x`, you will return only `x` steps. Return the current `url` after moving back in history **at most** `steps`.
* `string forward(int steps)` Move `steps` forward in history. If you can only forward `x` steps in the history and `steps > x`, you will forward only `x` steps. Return the current `url` after forwarding in history **at most** `steps`.
**Example:**
**Input:**
\[ "BrowserHistory ", "visit ", "visit ", "visit ", "back ", "back ", "forward ", "visit ", "forward ", "back ", "back "\]
\[\[ "leetcode.com "\],\[ "google.com "\],\[ "facebook.com "\],\[ "youtube.com "\],\[1\],\[1\],\[1\],\[ "linkedin.com "\],\[2\],\[2\],\[7\]\]
**Output:**
\[null,null,null,null, "facebook.com ", "google.com ", "facebook.com ",null, "linkedin.com ", "google.com ", "leetcode.com "\]
**Explanation:**
BrowserHistory browserHistory = new BrowserHistory( "leetcode.com ");
browserHistory.visit( "google.com "); // You are in "leetcode.com ". Visit "google.com "
browserHistory.visit( "facebook.com "); // You are in "google.com ". Visit "facebook.com "
browserHistory.visit( "youtube.com "); // You are in "facebook.com ". Visit "youtube.com "
browserHistory.back(1); // You are in "youtube.com ", move back to "facebook.com " return "facebook.com "
browserHistory.back(1); // You are in "facebook.com ", move back to "google.com " return "google.com "
browserHistory.forward(1); // You are in "google.com ", move forward to "facebook.com " return "facebook.com "
browserHistory.visit( "linkedin.com "); // You are in "facebook.com ". Visit "linkedin.com "
browserHistory.forward(2); // You are in "linkedin.com ", you cannot move forward any steps.
browserHistory.back(2); // You are in "linkedin.com ", move back two steps to "facebook.com " then to "google.com ". return "google.com "
browserHistory.back(7); // You are in "google.com ", you can move back only one step to "leetcode.com ". return "leetcode.com "
**Constraints:**
* `1 <= homepage.length <= 20`
* `1 <= url.length <= 20`
* `1 <= steps <= 100`
* `homepage` and `url` consist of '.' or lower case English letters.
* At most `5000` calls will be made to `visit`, `back`, and `forward`. | Count the frequency of each character. Loop over all character from 'a' to 'z' and append the character if it exists and decrease frequency by 1. Do the same from 'z' to 'a'. Keep repeating until the frequency of all characters is zero. |
Python short and clean. DoublyLinkedList. | design-browser-history | 0 | 1 | # Approach\nTL;DR, Same as [Official LinkedList solution](https://leetcode.com/problems/design-browser-history/editorial/)\n\n# Complexity\n`__init__` and `visit` functions:\n- Time complexity: $$O(1)$$\n\n- Space complexity: $$O(1)$$\n\n`back` and `forward` functions:\n- Time complexity: $$O(k)$$, where `k is number of steps`.\n\n- Space complexity: $$O(1)$$\n\n`n` calls to `visit` function:\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```python\nfrom dataclasses import dataclass\n\nclass BrowserHistory:\n\n def __init__(self, homepage: str):\n self.page = DLLNode(homepage)\n\n def visit(self, url: str) -> None:\n a, b = self.page, DLLNode(url)\n a.next, b.prev = b, a\n self.page = b\n\n def back(self, steps: int) -> str:\n while self.page.prev and steps: self.page = self.page.prev; steps -= 1\n return self.page.value\n\n def forward(self, steps: int) -> str:\n while self.page.next and steps: self.page = self.page.next; steps -= 1\n return self.page.value\n\n@dataclass\nclass DLLNode:\n value: Any = None\n prev: \'DLLNode | None\' = None\n next: \'DLLNode | None\' = None\n\n\n``` | 2 | Given an `m x n` binary matrix `mat`, return _the number of special positions in_ `mat`_._
A position `(i, j)` is called **special** if `mat[i][j] == 1` and all other elements in row `i` and column `j` are `0` (rows and columns are **0-indexed**).
**Example 1:**
**Input:** mat = \[\[1,0,0\],\[0,0,1\],\[1,0,0\]\]
**Output:** 1
**Explanation:** (1, 2) is a special position because mat\[1\]\[2\] == 1 and all other elements in row 1 and column 2 are 0.
**Example 2:**
**Input:** mat = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\]
**Output:** 3
**Explanation:** (0, 0), (1, 1) and (2, 2) are special positions.
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 100`
* `mat[i][j]` is either `0` or `1`. | Use two stack one for back history and one for forward history and simulate the functions. Can you do faster by using different data structure ? |
[Python] Top down spaghetti solution - Authentic like Italian cuisine | paint-house-iii | 0 | 1 | # Intuition\nWe first need to understand the idea of having neighborhoods. It the most basic sense, it\'s the number of color switch between different neighbors plus 1.\n\nFor example, `houses = [1, 2, 2, 1, 1]`, number of `color` switchs are `2`, and we have `3` neighborhoods.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nSimilar to other paint house problem, with a few conditions to check for the `houses` that had already been painted. Also we need to introduce a new variable `group` to count the number of time that we have different `colors` between neighbor.\n\n\n\n# Code\n```\nclass Solution:\n def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:\n\n @cache\n def dp(i, j, group):\n if i == len(cost) and group == target: return 0\n if i >= len(cost): return float("inf")\n if group > target: return float("inf")\n\n res = float("inf")\n if not houses[i]:\n for color in range(1, n + 1):\n if j != color:\n res = min(res, dp(i + 1, color, group + 1) + cost[i][color - 1])\n else:\n res = min(res, dp(i + 1, color, group) + cost[i][color - 1])\n else:\n color = houses[i]\n res = dp(i + 1, color, group + 1) if j != color else dp(i + 1, color, group)\n\n return res\n\n res = dp(0, -1, 0)\n return -1 if res == float("inf") else res\n``` | 1 | There is a row of `m` houses in a small city, each house must be painted with one of the `n` colors (labeled from `1` to `n`), some houses that have been painted last summer should not be painted again.
A neighborhood is a maximal group of continuous houses that are painted with the same color.
* For example: `houses = [1,2,2,3,3,2,1,1]` contains `5` neighborhoods `[{1}, {2,2}, {3,3}, {2}, {1,1}]`.
Given an array `houses`, an `m x n` matrix `cost` and an integer `target` where:
* `houses[i]`: is the color of the house `i`, and `0` if the house is not painted yet.
* `cost[i][j]`: is the cost of paint the house `i` with the color `j + 1`.
Return _the minimum cost of painting all the remaining houses in such a way that there are exactly_ `target` _neighborhoods_. If it is not possible, return `-1`.
**Example 1:**
**Input:** houses = \[0,0,0,0,0\], cost = \[\[1,10\],\[10,1\],\[10,1\],\[1,10\],\[5,1\]\], m = 5, n = 2, target = 3
**Output:** 9
**Explanation:** Paint houses of this way \[1,2,2,1,1\]
This array contains target = 3 neighborhoods, \[{1}, {2,2}, {1,1}\].
Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9.
**Example 2:**
**Input:** houses = \[0,2,1,2,0\], cost = \[\[1,10\],\[10,1\],\[10,1\],\[1,10\],\[5,1\]\], m = 5, n = 2, target = 3
**Output:** 11
**Explanation:** Some houses are already painted, Paint the houses of this way \[2,2,1,2,2\]
This array contains target = 3 neighborhoods, \[{2,2}, {1}, {2,2}\].
Cost of paint the first and last house (10 + 1) = 11.
**Example 3:**
**Input:** houses = \[3,1,2,3\], cost = \[\[1,1,1\],\[1,1,1\],\[1,1,1\],\[1,1,1\]\], m = 4, n = 3, target = 3
**Output:** -1
**Explanation:** Houses are already painted with a total of 4 neighborhoods \[{3},{1},{2},{3}\] different of target = 3.
**Constraints:**
* `m == houses.length == cost.length`
* `n == cost[i].length`
* `1 <= m <= 100`
* `1 <= n <= 20`
* `1 <= target <= m`
* `0 <= houses[i] <= n`
* `1 <= cost[i][j] <= 104` | Represent the counts (odd or even) of vowels with a bitmask. Precompute the prefix xor for the bitmask of vowels and then get the longest valid substring. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.