title
stringlengths 1
100
| titleSlug
stringlengths 3
77
| Java
int64 0
1
| Python3
int64 1
1
| content
stringlengths 28
44.4k
| voteCount
int64 0
3.67k
| question_content
stringlengths 65
5k
| question_hints
stringclasses 970
values |
---|---|---|---|---|---|---|---|
📌📌Python3 || 2007 ms, faster than 90.49% of Python3 || Clean and Easy to Understand | single-threaded-cpu | 0 | 1 | ```\ndef getOrder(self, tasks: List[List[int]]) -> List[int]:\n arr = []\n prev = 0\n output = [] \n tasks= sorted((tasks,i) for i,tasks in enumerate(tasks))\n for (m,n), i in tasks:\n while arr and prev < m:\n p,j,k = heappop(arr)\n prev = max(k,prev)+p\n output.append(j)\n heappush(arr,(n,i,m))\n return output+[i for _, i, _ in sorted(arr)]\n``` | 8 | You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the operation on the **same** pile more than once.
Return _the **minimum** possible total number of stones remaining after applying the_ `k` _operations_.
`floor(x)` is the **greatest** integer that is **smaller** than or **equal** to `x` (i.e., rounds `x` down).
**Example 1:**
**Input:** piles = \[5,4,9\], k = 2
**Output:** 12
**Explanation:** Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are \[5,4,5\].
- Apply the operation on pile 0. The resulting piles are \[3,4,5\].
The total number of stones in \[3,4,5\] is 12.
**Example 2:**
**Input:** piles = \[4,3,6,7\], k = 3
**Output:** 12
**Explanation:** Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are \[4,3,3,7\].
- Apply the operation on pile 3. The resulting piles are \[4,3,3,4\].
- Apply the operation on pile 0. The resulting piles are \[2,3,3,4\].
The total number of stones in \[2,3,3,4\] is 12.
**Constraints:**
* `1 <= piles.length <= 105`
* `1 <= piles[i] <= 104`
* `1 <= k <= 105` | To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks |
Simple python code with explanation | find-xor-sum-of-all-pairs-bitwise-and | 0 | 1 | ```\nclass Solution:\n #example 1 \n #result =[(1&6)^(1&5)^(2&6)^(2&5)^(3&6)^(3&5)]\n \\ / \\ / \\ /\n # (1&(6^5)) ^ (2&(6^5)) ^ (3&(6^5)) \n \\ | /\n \\ | /\n \\ | /\n \\ | /\n # ((1^2^3) & (6^5))\n def getXORSum(self, a, b):\n x = 0 \n for i in range(len(a)):\n x = x ^ a[i]\n y = 0 \n for j in range(len(b)):\n y = y ^ b[j]\n return x & y\n``` | 4 | The **XOR sum** of a list is the bitwise `XOR` of all its elements. If the list only contains one element, then its **XOR sum** will be equal to this element.
* For example, the **XOR sum** of `[1,2,3,4]` is equal to `1 XOR 2 XOR 3 XOR 4 = 4`, and the **XOR sum** of `[3]` is equal to `3`.
You are given two **0-indexed** arrays `arr1` and `arr2` that consist only of non-negative integers.
Consider the list containing the result of `arr1[i] AND arr2[j]` (bitwise `AND`) for every `(i, j)` pair where `0 <= i < arr1.length` and `0 <= j < arr2.length`.
Return _the **XOR sum** of the aforementioned list_.
**Example 1:**
**Input:** arr1 = \[1,2,3\], arr2 = \[6,5\]
**Output:** 0
**Explanation:** The list = \[1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5\] = \[0,1,2,0,2,1\].
The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.
**Example 2:**
**Input:** arr1 = \[12\], arr2 = \[4\]
**Output:** 4
**Explanation:** The list = \[12 AND 4\] = \[4\]. The XOR sum = 4.
**Constraints:**
* `1 <= arr1.length, arr2.length <= 105`
* `0 <= arr1[i], arr2[j] <= 109` | Compute the XOR of the numbers between 1 and n, and think about how it can be used. Let it be x. Think why n is odd. perm[0] = x XOR encoded[1] XOR encoded[3] XOR encoded[5] ... perm[i] = perm[i-1] XOR encoded[i-1] |
Simple python code with explanation | find-xor-sum-of-all-pairs-bitwise-and | 0 | 1 | ```\nclass Solution:\n #example 1 \n #result =[(1&6)^(1&5)^(2&6)^(2&5)^(3&6)^(3&5)]\n \\ / \\ / \\ /\n # (1&(6^5)) ^ (2&(6^5)) ^ (3&(6^5)) \n \\ | /\n \\ | /\n \\ | /\n \\ | /\n # ((1^2^3) & (6^5))\n def getXORSum(self, a, b):\n x = 0 \n for i in range(len(a)):\n x = x ^ a[i]\n y = 0 \n for j in range(len(b)):\n y = y ^ b[j]\n return x & y\n``` | 4 | You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`.
A string is called **balanced** if and only if:
* It is the empty string, or
* It can be written as `AB`, where both `A` and `B` are **balanced** strings, or
* It can be written as `[C]`, where `C` is a **balanced** string.
You may swap the brackets at **any** two indices **any** number of times.
Return _the **minimum** number of swaps to make_ `s` _**balanced**_.
**Example 1:**
**Input:** s = "\]\[\]\[ "
**Output:** 1
**Explanation:** You can make the string balanced by swapping index 0 with index 3.
The resulting string is "\[\[\]\] ".
**Example 2:**
**Input:** s = "\]\]\]\[\[\[ "
**Output:** 2
**Explanation:** You can do the following to make the string balanced:
- Swap index 0 with index 4. s = "\[\]\]\[\]\[ ".
- Swap index 1 with index 5. s = "\[\[\]\[\]\] ".
The resulting string is "\[\[\]\[\]\] ".
**Example 3:**
**Input:** s = "\[\] "
**Output:** 0
**Explanation:** The string is already balanced.
**Constraints:**
* `n == s.length`
* `2 <= n <= 106`
* `n` is even.
* `s[i]` is either `'['` or `']'`.
* The number of opening brackets `'['` equals `n / 2`, and the number of closing brackets `']'` equals `n / 2`. | Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[1]) ^ (arr2XorSum&arr1[2]) ^ ... = arr2XorSum & arr1XorSum. |
Easy Bit Manipulation [C++] [Js] [Python] | find-xor-sum-of-all-pairs-bitwise-and | 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:\nO(n+m)\n\n- Space complexity:\nO(1)\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int getXORSum(vector<int>& arr1, vector<int>& arr2){ \n // Variables\n int n = arr1.size(), m = arr2.size();\n int sum1 = 0, sum2 = 0;\n \n // Xor Operations\n for(int i=0; i<n; i++){\n sum1 ^= arr1[i];\n }\n for(int i=0; i<m; i++){\n sum2 ^= arr2[i];\n }\n\n // And Operation\n return sum1 & sum2;\n }\n};\n```\n```javascript []\n/**\n * @param {number[]} arr1\n * @param {number[]} arr2\n * @return {number}\n */\nvar getXORSum = function(arr1, arr2) {\n // Variables\n const n = arr1.length, m = arr2.length;\n let sum1 = 0, sum2 = 0;\n\n // XOR Operations\n for (let i = 0; i < n; i++) {\n sum1 ^= arr1[i];\n }\n for (let i = 0; i < m; i++) {\n sum2 ^= arr2[i];\n }\n\n // AND Operation\n return sum1 & sum2;\n};\n```\n```python []\nclass Solution:\n def getXORSum(self, arr1: List[int], arr2: List[int]) -> int:\n # Variables\n sum1 = 0\n sum2 = 0\n\n # XOR Operations\n for num in arr1:\n sum1 ^= num\n for num in arr2:\n sum2 ^= num\n\n # AND Operation\n return sum1 & sum2\n```\n | 0 | The **XOR sum** of a list is the bitwise `XOR` of all its elements. If the list only contains one element, then its **XOR sum** will be equal to this element.
* For example, the **XOR sum** of `[1,2,3,4]` is equal to `1 XOR 2 XOR 3 XOR 4 = 4`, and the **XOR sum** of `[3]` is equal to `3`.
You are given two **0-indexed** arrays `arr1` and `arr2` that consist only of non-negative integers.
Consider the list containing the result of `arr1[i] AND arr2[j]` (bitwise `AND`) for every `(i, j)` pair where `0 <= i < arr1.length` and `0 <= j < arr2.length`.
Return _the **XOR sum** of the aforementioned list_.
**Example 1:**
**Input:** arr1 = \[1,2,3\], arr2 = \[6,5\]
**Output:** 0
**Explanation:** The list = \[1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5\] = \[0,1,2,0,2,1\].
The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.
**Example 2:**
**Input:** arr1 = \[12\], arr2 = \[4\]
**Output:** 4
**Explanation:** The list = \[12 AND 4\] = \[4\]. The XOR sum = 4.
**Constraints:**
* `1 <= arr1.length, arr2.length <= 105`
* `0 <= arr1[i], arr2[j] <= 109` | Compute the XOR of the numbers between 1 and n, and think about how it can be used. Let it be x. Think why n is odd. perm[0] = x XOR encoded[1] XOR encoded[3] XOR encoded[5] ... perm[i] = perm[i-1] XOR encoded[i-1] |
Easy Bit Manipulation [C++] [Js] [Python] | find-xor-sum-of-all-pairs-bitwise-and | 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:\nO(n+m)\n\n- Space complexity:\nO(1)\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int getXORSum(vector<int>& arr1, vector<int>& arr2){ \n // Variables\n int n = arr1.size(), m = arr2.size();\n int sum1 = 0, sum2 = 0;\n \n // Xor Operations\n for(int i=0; i<n; i++){\n sum1 ^= arr1[i];\n }\n for(int i=0; i<m; i++){\n sum2 ^= arr2[i];\n }\n\n // And Operation\n return sum1 & sum2;\n }\n};\n```\n```javascript []\n/**\n * @param {number[]} arr1\n * @param {number[]} arr2\n * @return {number}\n */\nvar getXORSum = function(arr1, arr2) {\n // Variables\n const n = arr1.length, m = arr2.length;\n let sum1 = 0, sum2 = 0;\n\n // XOR Operations\n for (let i = 0; i < n; i++) {\n sum1 ^= arr1[i];\n }\n for (let i = 0; i < m; i++) {\n sum2 ^= arr2[i];\n }\n\n // AND Operation\n return sum1 & sum2;\n};\n```\n```python []\nclass Solution:\n def getXORSum(self, arr1: List[int], arr2: List[int]) -> int:\n # Variables\n sum1 = 0\n sum2 = 0\n\n # XOR Operations\n for num in arr1:\n sum1 ^= num\n for num in arr2:\n sum2 ^= num\n\n # AND Operation\n return sum1 & sum2\n```\n | 0 | You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`.
A string is called **balanced** if and only if:
* It is the empty string, or
* It can be written as `AB`, where both `A` and `B` are **balanced** strings, or
* It can be written as `[C]`, where `C` is a **balanced** string.
You may swap the brackets at **any** two indices **any** number of times.
Return _the **minimum** number of swaps to make_ `s` _**balanced**_.
**Example 1:**
**Input:** s = "\]\[\]\[ "
**Output:** 1
**Explanation:** You can make the string balanced by swapping index 0 with index 3.
The resulting string is "\[\[\]\] ".
**Example 2:**
**Input:** s = "\]\]\]\[\[\[ "
**Output:** 2
**Explanation:** You can do the following to make the string balanced:
- Swap index 0 with index 4. s = "\[\]\]\[\]\[ ".
- Swap index 1 with index 5. s = "\[\[\]\[\]\] ".
The resulting string is "\[\[\]\[\]\] ".
**Example 3:**
**Input:** s = "\[\] "
**Output:** 0
**Explanation:** The string is already balanced.
**Constraints:**
* `n == s.length`
* `2 <= n <= 106`
* `n` is even.
* `s[i]` is either `'['` or `']'`.
* The number of opening brackets `'['` equals `n / 2`, and the number of closing brackets `']'` equals `n / 2`. | Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[1]) ^ (arr2XorSum&arr1[2]) ^ ... = arr2XorSum & arr1XorSum. |
An Easy Solution with Explanation | find-xor-sum-of-all-pairs-bitwise-and | 0 | 1 | \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ncollect xor of each arry separately and then return the AND of both collections.\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\n```\nclass Solution:\n def getXORSum(self, arr1: List[int], arr2: List[int]) -> int:\n\n arr2_xor = arr2[0]\n for i in range(1, len(arr2)):\n arr2_xor ^= arr2[i]\n \n xor_arr1 = arr1[0]\n\n for i in range(1,len(arr1)):\n xor_arr1 ^= arr1[i]\n return xor_arr1 & arr2_xor\n``` | 0 | The **XOR sum** of a list is the bitwise `XOR` of all its elements. If the list only contains one element, then its **XOR sum** will be equal to this element.
* For example, the **XOR sum** of `[1,2,3,4]` is equal to `1 XOR 2 XOR 3 XOR 4 = 4`, and the **XOR sum** of `[3]` is equal to `3`.
You are given two **0-indexed** arrays `arr1` and `arr2` that consist only of non-negative integers.
Consider the list containing the result of `arr1[i] AND arr2[j]` (bitwise `AND`) for every `(i, j)` pair where `0 <= i < arr1.length` and `0 <= j < arr2.length`.
Return _the **XOR sum** of the aforementioned list_.
**Example 1:**
**Input:** arr1 = \[1,2,3\], arr2 = \[6,5\]
**Output:** 0
**Explanation:** The list = \[1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5\] = \[0,1,2,0,2,1\].
The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.
**Example 2:**
**Input:** arr1 = \[12\], arr2 = \[4\]
**Output:** 4
**Explanation:** The list = \[12 AND 4\] = \[4\]. The XOR sum = 4.
**Constraints:**
* `1 <= arr1.length, arr2.length <= 105`
* `0 <= arr1[i], arr2[j] <= 109` | Compute the XOR of the numbers between 1 and n, and think about how it can be used. Let it be x. Think why n is odd. perm[0] = x XOR encoded[1] XOR encoded[3] XOR encoded[5] ... perm[i] = perm[i-1] XOR encoded[i-1] |
An Easy Solution with Explanation | find-xor-sum-of-all-pairs-bitwise-and | 0 | 1 | \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ncollect xor of each arry separately and then return the AND of both collections.\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\n```\nclass Solution:\n def getXORSum(self, arr1: List[int], arr2: List[int]) -> int:\n\n arr2_xor = arr2[0]\n for i in range(1, len(arr2)):\n arr2_xor ^= arr2[i]\n \n xor_arr1 = arr1[0]\n\n for i in range(1,len(arr1)):\n xor_arr1 ^= arr1[i]\n return xor_arr1 & arr2_xor\n``` | 0 | You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`.
A string is called **balanced** if and only if:
* It is the empty string, or
* It can be written as `AB`, where both `A` and `B` are **balanced** strings, or
* It can be written as `[C]`, where `C` is a **balanced** string.
You may swap the brackets at **any** two indices **any** number of times.
Return _the **minimum** number of swaps to make_ `s` _**balanced**_.
**Example 1:**
**Input:** s = "\]\[\]\[ "
**Output:** 1
**Explanation:** You can make the string balanced by swapping index 0 with index 3.
The resulting string is "\[\[\]\] ".
**Example 2:**
**Input:** s = "\]\]\]\[\[\[ "
**Output:** 2
**Explanation:** You can do the following to make the string balanced:
- Swap index 0 with index 4. s = "\[\]\]\[\]\[ ".
- Swap index 1 with index 5. s = "\[\[\]\[\]\] ".
The resulting string is "\[\[\]\[\]\] ".
**Example 3:**
**Input:** s = "\[\] "
**Output:** 0
**Explanation:** The string is already balanced.
**Constraints:**
* `n == s.length`
* `2 <= n <= 106`
* `n` is even.
* `s[i]` is either `'['` or `']'`.
* The number of opening brackets `'['` equals `n / 2`, and the number of closing brackets `']'` equals `n / 2`. | Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[1]) ^ (arr2XorSum&arr1[2]) ^ ... = arr2XorSum & arr1XorSum. |
Python - one line | find-xor-sum-of-all-pairs-bitwise-and | 0 | 1 | # Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def getXORSum(self, arr1: List[int], arr2: List[int]) -> int:\n return reduce(xor, arr1) & reduce(xor, arr2)\n``` | 0 | The **XOR sum** of a list is the bitwise `XOR` of all its elements. If the list only contains one element, then its **XOR sum** will be equal to this element.
* For example, the **XOR sum** of `[1,2,3,4]` is equal to `1 XOR 2 XOR 3 XOR 4 = 4`, and the **XOR sum** of `[3]` is equal to `3`.
You are given two **0-indexed** arrays `arr1` and `arr2` that consist only of non-negative integers.
Consider the list containing the result of `arr1[i] AND arr2[j]` (bitwise `AND`) for every `(i, j)` pair where `0 <= i < arr1.length` and `0 <= j < arr2.length`.
Return _the **XOR sum** of the aforementioned list_.
**Example 1:**
**Input:** arr1 = \[1,2,3\], arr2 = \[6,5\]
**Output:** 0
**Explanation:** The list = \[1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5\] = \[0,1,2,0,2,1\].
The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.
**Example 2:**
**Input:** arr1 = \[12\], arr2 = \[4\]
**Output:** 4
**Explanation:** The list = \[12 AND 4\] = \[4\]. The XOR sum = 4.
**Constraints:**
* `1 <= arr1.length, arr2.length <= 105`
* `0 <= arr1[i], arr2[j] <= 109` | Compute the XOR of the numbers between 1 and n, and think about how it can be used. Let it be x. Think why n is odd. perm[0] = x XOR encoded[1] XOR encoded[3] XOR encoded[5] ... perm[i] = perm[i-1] XOR encoded[i-1] |
Python - one line | find-xor-sum-of-all-pairs-bitwise-and | 0 | 1 | # Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def getXORSum(self, arr1: List[int], arr2: List[int]) -> int:\n return reduce(xor, arr1) & reduce(xor, arr2)\n``` | 0 | You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`.
A string is called **balanced** if and only if:
* It is the empty string, or
* It can be written as `AB`, where both `A` and `B` are **balanced** strings, or
* It can be written as `[C]`, where `C` is a **balanced** string.
You may swap the brackets at **any** two indices **any** number of times.
Return _the **minimum** number of swaps to make_ `s` _**balanced**_.
**Example 1:**
**Input:** s = "\]\[\]\[ "
**Output:** 1
**Explanation:** You can make the string balanced by swapping index 0 with index 3.
The resulting string is "\[\[\]\] ".
**Example 2:**
**Input:** s = "\]\]\]\[\[\[ "
**Output:** 2
**Explanation:** You can do the following to make the string balanced:
- Swap index 0 with index 4. s = "\[\]\]\[\]\[ ".
- Swap index 1 with index 5. s = "\[\[\]\[\]\] ".
The resulting string is "\[\[\]\[\]\] ".
**Example 3:**
**Input:** s = "\[\] "
**Output:** 0
**Explanation:** The string is already balanced.
**Constraints:**
* `n == s.length`
* `2 <= n <= 106`
* `n` is even.
* `s[i]` is either `'['` or `']'`.
* The number of opening brackets `'['` equals `n / 2`, and the number of closing brackets `']'` equals `n / 2`. | Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[1]) ^ (arr2XorSum&arr1[2]) ^ ... = arr2XorSum & arr1XorSum. |
3 Line Solution | sum-of-digits-in-base-k | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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 sumBase(self, n: int, k: int) -> int:\n total = 0\n\n while n > 0:\n total += n % k\n n //= k\n\n return total\n``` | 0 | Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`.
After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`.
**Example 1:**
**Input:** n = 34, k = 6
**Output:** 9
**Explanation:** 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.
**Example 2:**
**Input:** n = 10, k = 10
**Output:** 1
**Explanation:** n is already in base 10. 1 + 0 = 1.
**Constraints:**
* `1 <= n <= 100`
* `2 <= k <= 10` | null |
✅✅✅99.81% faster and 97.35% on memory | sum-of-digits-in-base-k | 0 | 1 | # Intuition\n\n\n# Code\n```\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n a = 0\n while n!=0:\n if n//k:\n a+=n%k\n n//=k\n else:\n a+=n\n n=0\n return a\n``` | 1 | Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`.
After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`.
**Example 1:**
**Input:** n = 34, k = 6
**Output:** 9
**Explanation:** 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.
**Example 2:**
**Input:** n = 10, k = 10
**Output:** 1
**Explanation:** n is already in base 10. 1 + 0 = 1.
**Constraints:**
* `1 <= n <= 100`
* `2 <= k <= 10` | null |
[Python] - Divmod Solution | sum-of-digits-in-base-k | 0 | 1 | My thought process was:\n1) For base conversion we always need to use repeated divmod\n2) The result ist the leftover number and the residual is the current digit\n\n```\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n result = 0\n \n # make repeated divmods to get the digits and\n # the leftover number\n while n:\n n, res = divmod(n, k)\n result += res\n return result\n``` | 2 | Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`.
After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`.
**Example 1:**
**Input:** n = 34, k = 6
**Output:** 9
**Explanation:** 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.
**Example 2:**
**Input:** n = 10, k = 10
**Output:** 1
**Explanation:** n is already in base 10. 1 + 0 = 1.
**Constraints:**
* `1 <= n <= 100`
* `2 <= k <= 10` | null |
{Python3} easy solution | sum-of-digits-in-base-k | 0 | 1 | ```\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n output_sum = 0\n while (n > 0) :\n rem = n % k\n output_sum = output_sum + rem \n n = int(n / k)\n return output_sum\n``` | 5 | Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`.
After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`.
**Example 1:**
**Input:** n = 34, k = 6
**Output:** 9
**Explanation:** 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.
**Example 2:**
**Input:** n = 10, k = 10
**Output:** 1
**Explanation:** n is already in base 10. 1 + 0 = 1.
**Constraints:**
* `1 <= n <= 100`
* `2 <= k <= 10` | null |
[Python3] self-explained | sum-of-digits-in-base-k | 0 | 1 | \n```\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n ans = 0\n while n: \n n, x = divmod(n, k)\n ans += x\n return ans \n``` | 13 | Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`.
After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`.
**Example 1:**
**Input:** n = 34, k = 6
**Output:** 9
**Explanation:** 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.
**Example 2:**
**Input:** n = 10, k = 10
**Output:** 1
**Explanation:** n is already in base 10. 1 + 0 = 1.
**Constraints:**
* `1 <= n <= 100`
* `2 <= k <= 10` | null |
3-Lines Python Solution || 95% Faster || Memory less than 75% | sum-of-digits-in-base-k | 0 | 1 | ```\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n ans=0\n while n>0: ans+=n%k ; n//=k\n return ans\n```\n-----------------\n### ***Another 1-Line Solution***\n```\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n return (x:=lambda y: 0 if not y else y%k + x(y//k))(n)\n```\n-------------------\n***----- Taha Choura -----***\n*[email protected]* | 3 | Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`.
After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`.
**Example 1:**
**Input:** n = 34, k = 6
**Output:** 9
**Explanation:** 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.
**Example 2:**
**Input:** n = 10, k = 10
**Output:** 1
**Explanation:** n is already in base 10. 1 + 0 = 1.
**Constraints:**
* `1 <= n <= 100`
* `2 <= k <= 10` | null |
Easy solution || PYTHON | sum-of-digits-in-base-k | 0 | 1 | ```\n```class Solution:\n def sumBase(self, n: int, k: int) -> int:\n stri = ""\n while True:\n if n < k:\n break\n div = int(n // k)\n stri += str(n % k)\n n = div\n stri += str(n)\n stri = stri[::-1]\n lst = [int(x) for x in stri]\n return (sum(lst)) | 1 | Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`.
After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`.
**Example 1:**
**Input:** n = 34, k = 6
**Output:** 9
**Explanation:** 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.
**Example 2:**
**Input:** n = 10, k = 10
**Output:** 1
**Explanation:** n is already in base 10. 1 + 0 = 1.
**Constraints:**
* `1 <= n <= 100`
* `2 <= k <= 10` | null |
python solution fastest and efficient | sum-of-digits-in-base-k | 0 | 1 | ```\nclass Solution:\n def sumBase(self, n: int, k: int) -> int:\n x=[]\n while n!=0:\n x.append(n%k)\n n=n//k\n \n return sum(x)\n \n``` | 3 | Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`.
After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`.
**Example 1:**
**Input:** n = 34, k = 6
**Output:** 9
**Explanation:** 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.
**Example 2:**
**Input:** n = 10, k = 10
**Output:** 1
**Explanation:** n is already in base 10. 1 + 0 = 1.
**Constraints:**
* `1 <= n <= 100`
* `2 <= k <= 10` | null |
Python 100% Solution | frequency-of-the-most-frequent-element | 0 | 1 | # Typical Solution\n\n* 1043 ms\n\n```python\nclass Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n return max(iter_frequency(nums, k))\n\ndef iter_frequency(nums, k):\n window = deque()\n pre = 0\n for cur in sorted(nums):\n k -= (cur - pre) * len(window)\n while k < 0:\n k += cur - window.popleft()\n window.append(cur)\n yield len(window)\n pre = cur\n```\n\n# Faster Solution\n\n* Cuts down on extra sorting, by sorting only unique numbers.\n* Bulk updates the current k using division.\n* 911ms (by removing the generator, and unrolling the max)\n\n```python\nclass Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n return max(iter_frequency(nums, k))\n\ndef iter_frequency(nums, k):\n counter = Counter(nums)\n window = deque()\n total = 0\n pre = 0\n for cur in sorted(counter):\n cur_count = counter[cur]\n k -= (cur - pre) * total\n while k < 0:\n pre, pre_count = window[0]\n delta = cur - pre\n count = -(k // delta)\n if count >= pre_count:\n del window[0]\n k += delta * pre_count\n total -= pre_count\n else:\n k += delta * count\n window[0] = (pre, count_pre - count)\n total -= count\n break\n window.append((cur, cur_count))\n total += cur_count\n yield total\n pre = cur\n``` | 2 | The **frequency** of an element is the number of times it occurs in an array.
You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`.
Return _the **maximum possible frequency** of an element after performing **at most**_ `k` _operations_.
**Example 1:**
**Input:** nums = \[1,2,4\], k = 5
**Output:** 3
**Explanation:** Increment the first element three times and the second element two times to make nums = \[4,4,4\].
4 has a frequency of 3.
**Example 2:**
**Input:** nums = \[1,4,8,13\], k = 5
**Output:** 2
**Explanation:** There are multiple optimal solutions:
- Increment the first element three times to make nums = \[4,4,8,13\]. 4 has a frequency of 2.
- Increment the second element four times to make nums = \[1,8,8,13\]. 8 has a frequency of 2.
- Increment the third element five times to make nums = \[1,4,13,13\]. 13 has a frequency of 2.
**Example 3:**
**Input:** nums = \[3,9,6\], k = 2
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105`
* `1 <= k <= 105` | Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing. |
【Video】Give me 10 minutes - How we think about a solution | frequency-of-the-most-frequent-element | 1 | 1 | # Intuition\nSorting input array and use slinding window technique.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/MbCFzt4v1uE\n\n\u203B Since I recorded that video last year, there might be parts that could be unclear. If you have any questions, feel free to leave a comment.\n\n\u25A0 Timeline of the video\n\n`0:00` Read the question of Frequency of the Most Frequent Element\n`1:11` Explain a basic idea to solve Frequency of the Most Frequent Element\n`11:48` Coding\n`14:21` Summarize the algorithm of Frequency of the Most Frequent Element\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,139\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n**My channel reached 3,000 subscribers these days. Thank you so much for your support!**\n\n---\n\n# Approach\n\n## How we think about a solution\n\nLet\'s think about this case.\n\n```\nInput = [1,3,3,5,5] k = 4\n```\n\nI already sorted input array. Sorting is good idea because sorting makes it easier to group similar magnitudes next to each other, facilitating the creation of identical numbers.\n\nFor example, we try to make 3 three times. Let\'s compare sorted array and unsorted array.\n```\nSorted: [1,3,3,5,5]\u2192[3,3,3,5,5]\nUnsroted: [1,5,3,5,3]\u2192[3,5,3,5,3]\n```\nSeems like sorted array is easier to find numbers we should increase. In addition to that, there is no order constraints for this question.\n\nTo check adjacent numbers after sorting the input array, we use sliding window technique.\n\n**Basically, we are trying to make all the numbers same in the window.**\n\nWe are allowed to increase numbers `k` times. when we try to make all numbers same in the window, simply \n\n---\n\n\u2B50\uFE0F Points\n\n```\ncurrent number * range of window > current window total + k\n```\n\nIf we meet the condition, we need to shorten window size, because we cannot change all numbers in window to the same number.\n\nFor example, \n```\ninput = [1,3,3,5,5], k = 1\n```\nLet\'s say we are now at `index 1` and try to make two `3` from `index 0` to `index 1`.\n\nIn that case, we need `6` to make all numbers `3`.(= `3`(current number) * `2`(range of window)), but current window total is `4`(= `1` + `3`). we perform `1` time, so we can deal with up to `5`.\n\nOne time short. That\'s why we need to shorten window size.\n\n- What if `k = 2`?\n\nWith the formula, `6` > `6`. it\'s false. In that case, we can expand window size, because if we add `2` to `index 0`, we can create `[3,3,3,5,5]`.\n\nIn other words, we can consider window size as maximum possible frequency of an element.\n\n---\n\nLet\'s see one by one.\n\nWe use two pointers `left` and `right` starging from index `0`.\n```\n[1,3,3,5,5] k = 4\n L\n R\n\nwindow total = 1 (= between left and right)\n```\nNow window total is `1`. Let\'s decide window size with the formula.\n\n```\ncurrent number * range of window > current window total + k\n\ncurrent number: 1(= right number)\nrange of window: 0(= right) - 0(= left) + 1\ncurrent window total: 1\nk: 4\n\n1 * 1 > 1 + 4\n1 > 5\n\u2192 false\n\n```\n`1 * 1` means total number in the window if we make all numbers same.\n`1 + 4` means maximum number after we perform increament.\n\nIt\'s false, just compare current window size with current maximum window size and take a large size. \n\n```\nmax(res, right - left + 1)\n= 0 vs 1\n\nres = 1\n```\nLet\'s move next.\n```\n[1,3,3,5,5] k = 4\n L R\n \nwindow total = 4 (= between left and right)\nres = 1 (= max window size = maximum possible frequency of an element)\n```\nDecide window size with the formula\n\n```\ncurrent number * range of window > current window total + k\n= 3 * 2 > 4 + 4\n\u2192 false\n\n6 is total number in window if we make all numbers 3 in window.\nWe can deal with up to 8.\n\nWe can expand the window size\n\nres = 2 (1(= res) vs 1(= right) - 0(= left) + 1)\n```\nLet\'s move next.\n```\n[1,3,3,5,5] k = 4\n L R\n \nwindow total = 7\nres = 2\n```\nDecide window size with the formula\n```\ncurrent number * range of window > current window total + k\n= 3 * 3 > 7 + 4\n\u2192 false\n\nWe can expand the window size\n\nres = 3 (= 2 vs 2 - 0 + 1)\n```\n\nLet\'s move next.\n```\n[1,3,3,5,5] k = 4\n L R\n \nwindow total = 12\nres = 3\n```\nDecide window size with the formula\n```\ncurrent number * range of window > current window total + k\n= 5 * 4 > 12 + 4\n\u2192 true\n\nWe cannot make all numbers 5 in the window.\nWe will shorten window size\n```\nMove `left` pointer to next and subtract current left number(= 1) from window total, because it will be out of bounds from the window.\n```\n[1,3,3,5,5] k = 4\n L R\n \nwindow total = 11\nres = 3\n```\nDecide window size with the formula again.\n```\ncurrent number * range of window > current window total + k\n= 5 * 3 > 11 + 4\n\u2192 false\n\nWe can make all numbers 5 in the window.\n\nCalculate window size\nres = 3 (= 3 vs 3 - 1 + 1)\n```\nLet\'s move next.\n```\n[1,3,3,5,5] k = 4\n L R\n \nwindow total = 16\nres = 3\n```\nDecide window size with the formula\n```\ncurrent number * range of window > current window total + k\n= 5 * 4 > 16 + 4\n\u2192 false\n\nWe can expand the window size\n\nres = 4 (= 3 vs 4 - 1 + 1)\n```\nThen finish iteration.\n```\nOutput: 4\n```\nLet\'s check.\n```\n[1,3,3,5,5] k = 4\n L R\n\nAdd 2 to index 1.\n[1,5,3,5,5] k = 2\n L R\n\nAdd 2 to index 2.\n[1,5,5,5,5] k = 0\n L R\n```\nWe can create four 5 in the window.\n\nLet\'s see a real algorithm!\n\n\n---\n\n\n\n### Algorithm Overview\n\nThe algorithm aims to find the maximum frequency of an element that can be obtained by performing at most `k` operations on the array.\n\n### Detailed Explanation\n\n1. **Sort the input array:**\n - **Code:**\n ```python\n nums.sort()\n ```\n - **Explanation:**\n Sorts the input array in ascending order. Sorting is essential for grouping similar magnitudes together, facilitating subsequent operations.\n\n2. **Initialize variables:**\n - **Code:**\n ```python\n left = right = res = total = 0\n ```\n - **Explanation:**\n Initializes variables to keep track of the current window (`left` and `right` pointers), the maximum frequency (`res`), and the total sum (`total`) within the window.\n\n3. **Sliding Window Approach:**\n - **Code:**\n ```python\n while right < len(nums):\n total += nums[right]\n\n while nums[right] * (right - left + 1) > total + k:\n total -= nums[left]\n left += 1\n \n res = max(res, right - left + 1)\n right += 1\n ```\n - **Explanation:**\n - The outer loop (`while right < len(nums)`) iterates through the array, expanding the window to the right.\n - The inner loop (`while nums[right] * (right - left + 1) > total + k`) contracts the window from the left if the current window violates the condition specified by `k`.\n - Updates the maximum frequency (`res`) with the size of the current window.\n - Moves the right pointer to expand the window.\n\n4. **Return the result:**\n - **Code:**\n ```python\n return res\n ```\n - **Explanation:**\n Returns the maximum frequency obtained after performing at most `k` operations.\n\n# Complexity\n- Time complexity: $$O(n log n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(log n)$$ or $$O(n)$$\nDepends on language you use. Sorting need some extra space.\n\n```python []\nclass Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n \n nums.sort()\n left = right = res = total = 0\n\n while right < len(nums):\n total += nums[right]\n\n while nums[right] * (right - left + 1) > total + k:\n total -= nums[left]\n left += 1\n \n res = max(res, right - left + 1)\n right += 1\n \n return res\n```\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar maxFrequency = function(nums, k) {\n nums.sort((a, b) => a - b);\n let left = 0, right = 0, res = 0, total = 0;\n\n while (right < nums.length) {\n total += nums[right];\n\n while (nums[right] * (right - left + 1) > total + k) {\n total -= nums[left];\n left += 1;\n }\n\n res = Math.max(res, right - left + 1);\n right += 1;\n }\n\n return res; \n};\n```\n```java []\nclass Solution {\n public int maxFrequency(int[] nums, int k) {\n Arrays.sort(nums);\n int left = 0, right = 0;\n long res = 0, total = 0;\n\n while (right < nums.length) {\n total += nums[right];\n\n while (nums[right] * (right - left + 1L) > total + k) {\n total -= nums[left];\n left += 1;\n }\n\n res = Math.max(res, right - left + 1L);\n right += 1;\n }\n\n return (int) res; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int maxFrequency(vector<int>& nums, int k) {\n sort(nums.begin(), nums.end());\n int left = 0, right = 0;\n long res = 0, total = 0;\n\n while (right < nums.size()) {\n total += nums[right];\n\n while (nums[right] * static_cast<long>(right - left + 1) > total + k) {\n total -= nums[left];\n left += 1;\n }\n\n res = max(res, static_cast<long>(right - left + 1));\n right += 1;\n }\n\n return static_cast<int>(res); \n }\n};\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### My next daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/solutions/4306758/video-give-me-9-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/Tf69tOpE4GE\n\n\u25A0 Timeline of the video\n\n`0:05` Try to find a solution pattern\n`1:44` What if we have the same numbers in input array?\n`5:37` Why it works when we skip reduction\n`7:22` Coding\n`8:52` Time Complexity and Space Complexity\n\n### My previous daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/minimize-maximum-pair-sum-in-array/solutions/4297828/video-give-me-u-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/DzzjWJdhNhI\n\n\u25A0 Timeline of the video\n\n`0:04` Explain how we can solve Minimize Maximum Pair Sum in Array\n`2:21` Check with other pair combinations\n`4:12` Let\'s see another example!\n`5:37` Find Common process of the two examples\n`6:45` Coding\n`7:55` Time Complexity and Space Complexity | 45 | The **frequency** of an element is the number of times it occurs in an array.
You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`.
Return _the **maximum possible frequency** of an element after performing **at most**_ `k` _operations_.
**Example 1:**
**Input:** nums = \[1,2,4\], k = 5
**Output:** 3
**Explanation:** Increment the first element three times and the second element two times to make nums = \[4,4,4\].
4 has a frequency of 3.
**Example 2:**
**Input:** nums = \[1,4,8,13\], k = 5
**Output:** 2
**Explanation:** There are multiple optimal solutions:
- Increment the first element three times to make nums = \[4,4,8,13\]. 4 has a frequency of 2.
- Increment the second element four times to make nums = \[1,8,8,13\]. 8 has a frequency of 2.
- Increment the third element five times to make nums = \[1,4,13,13\]. 13 has a frequency of 2.
**Example 3:**
**Input:** nums = \[3,9,6\], k = 2
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105`
* `1 <= k <= 105` | Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing. |
✅ Python3 | Sliding Window | Beats 97% ✅ | frequency-of-the-most-frequent-element | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe initial idea is that we need to calculate, for every number in the array, how many numbers we can get to match that number after at most $k$ operations.\n\nThe next idea that comes to mind is that in order to use the $k$ operations to the fullest, we should try to use them on numbers that are already relatively close to (but not larget than) the target number we are trying to reach. Sorting the array lends itself well to this strategy, because for each element in the sorted array, we know the elements directly before the target element are the closest in value.\n\nFinally, we can realize that once we have found a target $t$ such that the preceeding $n$ values can be transformed into $t$ in under $k$ operations, we never have to consider a window of size less than $n$ again, because that can\'t possibly be our answer.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nBegin by defining the start and end of a \'window\'. Both pointers will initially point to the last index in the array. The window represents the start and end of a subarray of nums that we are trying to transform into the target number. The target number is the last element in the window.\n\nFor each iteration, the difference between ```windowEnd``` and ```windowStart``` should be the size of the largest subarray of ```nums``` that we are able to transform into a single target number, although ```windowStart``` and ```windowEnd``` don\'t necessarily correspond to the start and end of that particular subarray.\n\nWe also keep track of the total number of operations we need to transform all of the elements from ```windowStart``` to ```windowEnd``` to have the same value as the element at ```windowEnd```.\n\nDuring each step, if we are able to transform all of the numbers within the window into the target number, then we expand the window to include another element from ```nums```, by decrementing ```windowStart```. If we are unable to transform all of the numbers into the target, then we decrease the target, by decrementing ```windowEnd```.\n\nIn the end, we know that the size of the largest window in which we are able to transform all of the elements into the target element is of size ```windowEnd-windowStart+1```.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n$O(n\\log(n))$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n$O(1)$\n\n# Code\n```\nclass Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n nums.sort()\n windowStart = windowEnd = len(nums) - 1\n area = 0\n\n while windowStart:\n windowStart -= 1\n area += nums[windowEnd] - nums[windowStart]\n if k < area:\n diff = nums[windowEnd] - nums[windowEnd-1]\n area -= diff * (windowEnd - windowStart)\n windowEnd -= 1\n return windowEnd - windowStart + 1\n``` | 1 | The **frequency** of an element is the number of times it occurs in an array.
You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`.
Return _the **maximum possible frequency** of an element after performing **at most**_ `k` _operations_.
**Example 1:**
**Input:** nums = \[1,2,4\], k = 5
**Output:** 3
**Explanation:** Increment the first element three times and the second element two times to make nums = \[4,4,4\].
4 has a frequency of 3.
**Example 2:**
**Input:** nums = \[1,4,8,13\], k = 5
**Output:** 2
**Explanation:** There are multiple optimal solutions:
- Increment the first element three times to make nums = \[4,4,8,13\]. 4 has a frequency of 2.
- Increment the second element four times to make nums = \[1,8,8,13\]. 8 has a frequency of 2.
- Increment the third element five times to make nums = \[1,4,13,13\]. 13 has a frequency of 2.
**Example 3:**
**Input:** nums = \[3,9,6\], k = 2
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105`
* `1 <= k <= 105` | Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing. |
Easiest Solution | frequency-of-the-most-frequent-element | 0 | 1 | \nThis algorithm uses a sliding window approach to efficiently find the maximum frequency while considering the constraints on the number of operations.\n\n# Approach\nTo solve this problem, you can follow these steps:\n\n1. Sort the input array `nums` in ascending order.\n2. Initialize a variable `left` to 0 to represent the left boundary of the window, and initialize a variable `maxFreq` to 0 to store the maximum frequency.\n3. Iterate through the array with a variable `right` representing the right boundary of the window.\n4. Calculate the total number of operations needed to make all elements in the current window equal. This can be done by multiplying the difference between the current element and the previous element by the distance between the current and previous elements.\n5. If the total operations exceed `k`, move the left boundary of the window to the right.\n6. Update the maximum frequency based on the current window size.\n7. Continue this process until you reach the end of the array.\n\n\n# Code\n```\nclass Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n \n nums.sort()\n left = 0\n maxFreq = 0\n operations = 0\n \n for right in range(len(nums)):\n operations += (nums[right] - nums[right - 1]) * (right - left)\n \n while operations > k:\n operations -= nums[right] - nums[left]\n left += 1\n \n maxFreq = max(maxFreq, right - left + 1)\n \n return maxFreq\n\n\n```\n# **PLEASE DO UPVOTE!!!** | 7 | The **frequency** of an element is the number of times it occurs in an array.
You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`.
Return _the **maximum possible frequency** of an element after performing **at most**_ `k` _operations_.
**Example 1:**
**Input:** nums = \[1,2,4\], k = 5
**Output:** 3
**Explanation:** Increment the first element three times and the second element two times to make nums = \[4,4,4\].
4 has a frequency of 3.
**Example 2:**
**Input:** nums = \[1,4,8,13\], k = 5
**Output:** 2
**Explanation:** There are multiple optimal solutions:
- Increment the first element three times to make nums = \[4,4,8,13\]. 4 has a frequency of 2.
- Increment the second element four times to make nums = \[1,8,8,13\]. 8 has a frequency of 2.
- Increment the third element five times to make nums = \[1,4,13,13\]. 13 has a frequency of 2.
**Example 3:**
**Input:** nums = \[3,9,6\], k = 2
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105`
* `1 <= k <= 105` | Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing. |
✅☑[C++/Java/Python/JavaScript] || 3 Approaches || EXPLAINED🔥 | frequency-of-the-most-frequent-element | 1 | 1 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Sliding Window)***\n1. Sort the `nums` array in ascending order to ensure that the elements are in non-decreasing order.\n\n1. Initialize two pointers, `left` and `right`, both starting at the beginning (0) of the sorted array. `left` represents the `left` end of the subarray, and `right` represents the `right` end.\n\n1. Initialize two variables, `ans` (for storing the maximum subarray length) and `curr` (for storing the sum of elements in the current subarray).\n\n1. Iterate through the `nums` array with the `right` pointer, starting from index 0 and moving to the end of the array.\n\n1. For each element `target` at index `right`, add it to the `curr` sum to represent the addition of the element to the subarray.\n\n1. Use a while loop to adjust the subarray size while maintaining the condition that increasing all elements in the subarray (from `left` to `right`) by at most k should result in a strictly increasing subarray. The condition being checked is `(right - left + 1) * target - curr > k`.\n\n - If this condition is met, it means that the current subarray doesn\'t satisfy the requirement of increasing each element by at most `k`. In this case, reduce the subarray size by removing the element at the `left` pointer. This is done by subtracting `nums[left]` from `curr` and incrementing `left`.\n1. In each iteration, update `ans` by taking the maximum of the current `ans` and the length of the subarray from `left` to `right`, which is `right - left + 1`.\n\n1. Continue iterating through the array, adjusting the subarray size as necessary, and updating `ans` until you reach the end of the array.\n\n1. After the loop finishes, `ans` will contain the maximum length of a subarray that satisfies the condition of increasing each element by at most `k`.\n\n1. Return `ans` as the result.\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 int maxFrequency(vector<int>& nums, int k) {\n sort(nums.begin(), nums.end());\n int left = 0;\n int ans = 0;\n long curr = 0;\n \n for (int right = 0; right < nums.size(); right++) {\n long target = nums[right];\n curr += target;\n \n while ((right - left + 1) * target - curr > k) {\n curr -= nums[left];\n left++;\n }\n \n ans = max(ans, right - left + 1);\n }\n \n return ans;\n }\n};\n\n```\n\n```C []\n\nint maxFrequency(int* nums, int numsSize, int k) {\n // Sort the nums array in ascending order\n qsort(nums, numsSize, sizeof(int), cmp);\n \n int left = 0;\n int ans = 0;\n long curr = 0;\n \n for (int right = 0; right < numsSize; right++) {\n long target = nums[right];\n curr += target;\n \n while ((right - left + 1) * target - curr > k) {\n curr -= nums[left];\n left++;\n }\n \n ans = fmax(ans, right - left + 1);\n }\n \n return ans;\n}\n\n\n```\n\n```Java []\nclass Solution {\n public int maxFrequency(int[] nums, int k) {\n Arrays.sort(nums);\n int left = 0;\n int ans = 0;\n long curr = 0;\n \n for (int right = 0; right < nums.length; right++) {\n int target = nums[right];\n curr += target;\n \n while ((right - left + 1) * target - curr > k) {\n curr -= nums[left];\n left++;\n }\n \n ans = Math.max(ans, right - left + 1);\n }\n \n return ans;\n }\n}\n\n```\n\n```python3 []\nclass Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n nums.sort()\n left = 0\n ans = 0\n curr = 0\n \n for right in range(len(nums)):\n target = nums[right]\n curr += target\n \n while (right - left + 1) * target - curr > k:\n curr -= nums[left]\n left += 1\n \n ans = max(ans, right - left + 1)\n\n return ans\n```\n\n\n```javascript []\nvar maxFrequency = function(nums, k) {\n nums.sort((a, b) => a - b);\n let left = 0;\n let ans = 0;\n let curr = 0;\n\n for (let right = 0; right < nums.length; right++) {\n const target = nums[right];\n curr += target;\n\n while ((right - left + 1) * target - curr > k) {\n curr -= nums[left];\n left++;\n }\n\n ans = Math.max(ans, right - left + 1);\n }\n\n return ans;\n};\n\n```\n\n\n---\n\n#### ***Approach 2( Advanced sliding Window)***\n1. The code sorts the input array in ascending order to make it easier to work with.\n\n1. It uses two pointers, `i` and `j`, to represent the window. The `sum` variable keeps track of the sum of elements within the window, and `maxlen` stores the maximum window length.\n\n1. The outer loop (controlled by `j`) iterates through the array elements and expands the window by adding elements to `sum`.\n\n1. The inner `while` loop adjusts the window size to maximize the window length without exceeding `k`. It does so by removing elements from the left end (incrementing `i`) until the condition is met.\n\n1. The maximum window length is updated whenever a longer window is found.\n\n# Complexity\n- *Time complexity:*\n $$O(nlogn)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int maxFrequency(vector<int>& nums, int k) {\n int n = nums.size();\n sort(nums.begin(), nums.end()); // Sort the input array in ascending order.\n\n int i = 0; // Initialize a pointer i at the beginning of the sorted array.\n long long sum = 0; // Initialize a variable to keep track of the sum of elements within the window.\n int maxlen = 1; // Initialize the maximum window length.\n\n for (int j = 0; j < n; j++) {\n sum += nums[j]; // Add the current element to the sum.\n \n // Use a while loop to adjust the window size to maximize the window length without exceeding k.\n while (1LL * nums[j] * (j - i + 1) > sum + k) {\n sum -= nums[i]; // Remove the element at position i from the window.\n i++; // Increment i to make the window smaller (moving the left end to the right).\n }\n\n maxlen = max(maxlen, j - i + 1); // Update the maximum window length.\n }\n\n return maxlen; // Return the maximum window length.\n }\n};\n\n\n```\n\n```C []\n\nint maxFrequency(int* nums, int numsSize, int k) {\n qsort(nums, numsSize, sizeof(int), compare); // Sort the input array in ascending order.\n\n int i = 0; // Initialize a pointer i at the beginning of the sorted array.\n long long sum = 0; // Initialize a variable to keep track of the sum of elements within the window.\n int maxlen = 1; // Initialize the maximum window length.\n\n for (int j = 0; j < numsSize; j++) {\n sum += nums[j]; // Add the current element to the sum.\n\n // Use a while loop to adjust the window size to maximize the window length without exceeding k.\n while (1LL * nums[j] * (j - i + 1) > sum + k) {\n sum -= nums[i]; // Remove the element at position i from the window.\n i++; // Increment i to make the window smaller (moving the left end to the right).\n }\n\n maxlen = maxlen > (j - i + 1) ? maxlen : (j - i + 1); // Update the maximum window length.\n }\n\n return maxlen; // Return the maximum window length.\n}\n\n\n```\n\n```Java []\npublic int maxFrequency(int[] nums, int k) {\n Arrays.sort(nums); // Sort the input array in ascending order.\n\n int i = 0; // Initialize a pointer i at the beginning of the sorted array.\n long sum = 0; // Initialize a variable to keep track of the sum of elements within the window.\n int maxlen = 1; // Initialize the maximum window length.\n\n for (int j = 0; j < nums.length; j++) {\n sum += nums[j]; // Add the current element to the sum.\n\n // Use a while loop to adjust the window size to maximize the window length without exceeding k.\n while ((long)nums[j] * (j - i + 1) > sum + k) {\n sum -= nums[i]; // Remove the element at position i from the window.\n i++; // Increment i to make the window smaller (moving the left end to the right).\n }\n\n maxlen = Math.max(maxlen, j - i + 1); // Update the maximum window length.\n }\n\n return maxlen; // Return the maximum window length.\n}\n\n\n```\n\n```python3 []\ndef maxFrequency(nums, k):\n nums.sort() # Sort the input array in ascending order.\n\n i = 0 # Initialize a pointer i at the beginning of the sorted array.\n total = 0 # Initialize a variable to keep track of the sum of elements within the window.\n maxlen = 1 # Initialize the maximum window length.\n\n for j in range(len(nums)):\n total += nums[j] # Add the current element to the total sum.\n\n # Use a while loop to adjust the window size to maximize the window length without exceeding k.\n while nums[j] * (j - i + 1) > total + k:\n total -= nums[i] # Remove the element at position i from the window.\n i += 1 # Increment i to make the window smaller (moving the left end to the right).\n\n maxlen = max(maxlen, j - i + 1) # Update the maximum window length.\n\n return maxlen # Return the maximum window length.\n\n```\n\n\n```javascript []\nvar maxFrequency = function(nums, k) {\n nums.sort((a, b) => a - b); // Sort the input array in ascending order.\n\n let i = 0; // Initialize a pointer i at the beginning of the sorted array.\n let sum = 0; // Initialize a variable to keep track of the sum of elements within the window.\n let maxlen = 1; // Initialize the maximum window length.\n\n for (let j = 0; j < nums.length; j++) {\n sum += nums[j]; // Add the current element to the sum.\n\n // Use a while loop to adjust the window size to maximize the window length without exceeding k.\n while (nums[j] * (j - i + 1) > sum + k) {\n sum -= nums[i]; // Remove the element at position i from the window.\n i++; // Increment i to make the window smaller (moving the left end to the right).\n }\n\n maxlen = Math.max(maxlen, j - i + 1); // Update the maximum window length.\n }\n\n return maxlen; // Return the maximum window length.\n};\n\n```\n\n\n---\n#### ***Approach 3***\n1. **Sort the Input Array:**\n\n - The function starts by sorting the `nums` array in non-decreasing order. Sorting is essential for implementing the sliding window technique efficiently.\n1. **Sliding Window Approach:**\n\n - The algorithm employs a sliding window approach to find the maximum frequency.\n - It uses pointers `i` and `j` to define a window where the elements can be adjusted by at most `k` operations.\n - `kk` keeps track of the remaining operations available.\n1. **Calculating Frequency:**\n\n - For each `i`, it calculates the total difference required to make the elements within the window equal.\n - The difference is subtracted from `kk`, and the window is adjusted accordingly until `kk` is non-negative.\n1. **Updating Maximum Frequency:**\n\n - At each step, it updates `maxlen` with the maximum window size encountered so far.\n\n# Complexity\n- *Time complexity:*\n $$O(nlogn)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n# Code\n```C++ []\nclass Solution {\npublic:\n int maxFrequency(vector<int>& nums, int k) {\n int n = nums.size();\n // Sort the input array in non-decreasing order\n sort(nums.begin(), nums.end());\n int maxlen = 1; // Variable to store the maximum frequency\n\n // Use long long for the operations involving k to prevent overflow\n long long kk = k;\n\n int j = 0; // Left pointer of the sliding window\n\n // Loop through the array starting from the second element\n for (int i = 1; i < n; ++i) {\n // Calculate the total difference needed to make the elements in the window equal\n kk -= static_cast<long long>(nums[i] - nums[i - 1]) * (i - j);\n\n // Adjust the window by moving the left pointer as needed\n while (kk < 0) {\n kk += nums[i] - nums[j];\n ++j;\n }\n\n // Update the maxlen with the maximum window size\n maxlen = max(maxlen, i - j + 1);\n }\n\n return maxlen; // Return the maximum frequency\n }\n};\n\n```\n```C []\n\n\nint maxFrequency(int* nums, int numsSize, int k) {\n // Sort the input array in non-decreasing order\n qsort(nums, numsSize, sizeof(int), cmpfunc);\n int maxlen = 1; // Variable to store the maximum frequency\n\n // Use long long for the operations involving k to prevent overflow\n long long kk = k;\n\n int j = 0; // Left pointer of the sliding window\n\n // Loop through the array starting from the second element\n for (int i = 1; i < numsSize; ++i) {\n // Calculate the total difference needed to make the elements in the window equal\n kk -= (long long)(nums[i] - nums[i - 1]) * (i - j);\n\n // Adjust the window by moving the left pointer as needed\n while (kk < 0) {\n kk += nums[i] - nums[j];\n ++j;\n }\n\n // Update the maxlen with the maximum window size\n maxlen = maxlen > (i - j + 1) ? maxlen : (i - j + 1);\n }\n\n return maxlen; // Return the maximum frequency\n}\n\nint cmpfunc(const void* a, const void* b) {\n return (*(int*)a - *(int*)b);\n}\n\n```\n```java []\n\n\nclass Solution {\n public int maxFrequency(int[] nums, int k) {\n Arrays.sort(nums);\n int maxlen = 1;\n long kk = k;\n int j = 0;\n\n for (int i = 1; i < nums.length; ++i) {\n kk -= (long)(nums[i] - nums[i - 1]) * (i - j);\n while (kk < 0) {\n kk += nums[i] - nums[j];\n j++;\n }\n\n maxlen = Math.max(maxlen, i - j + 1);\n }\n\n return maxlen;\n }\n}\n\n```\n```python3 []\nclass Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n nums.sort()\n maxlen = 1\n kk = k\n j = 0\n\n for i in range(1, len(nums)):\n kk -= (nums[i] - nums[i - 1]) * (i - j)\n while kk < 0:\n kk += nums[i] - nums[j]\n j += 1\n\n maxlen = max(maxlen, i - j + 1)\n\n return maxlen\n\n```\n```javascript []\nvar maxFrequency = function(nums, k) {\n nums.sort((a, b) => a - b);\n let maxlen = 1;\n let kk = k;\n let j = 0;\n\n for (let i = 1; i < nums.length; ++i) {\n kk -= (nums[i] - nums[i - 1]) * (i - j);\n\n while (kk < 0) {\n kk += nums[i] - nums[j];\n ++j;\n }\n\n maxlen = Math.max(maxlen, i - j + 1);\n }\n\n return maxlen;\n};\n\n```\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n--- | 6 | The **frequency** of an element is the number of times it occurs in an array.
You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`.
Return _the **maximum possible frequency** of an element after performing **at most**_ `k` _operations_.
**Example 1:**
**Input:** nums = \[1,2,4\], k = 5
**Output:** 3
**Explanation:** Increment the first element three times and the second element two times to make nums = \[4,4,4\].
4 has a frequency of 3.
**Example 2:**
**Input:** nums = \[1,4,8,13\], k = 5
**Output:** 2
**Explanation:** There are multiple optimal solutions:
- Increment the first element three times to make nums = \[4,4,8,13\]. 4 has a frequency of 2.
- Increment the second element four times to make nums = \[1,8,8,13\]. 8 has a frequency of 2.
- Increment the third element five times to make nums = \[1,4,13,13\]. 13 has a frequency of 2.
**Example 3:**
**Input:** nums = \[3,9,6\], k = 2
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105`
* `1 <= k <= 105` | Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing. |
[Python3] greedy | longest-substring-of-all-vowels-in-order | 0 | 1 | \n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n vowels = "aeiou"\n ans = 0\n cnt = prev = -1 \n for i, x in enumerate(word): \n curr = vowels.index(x)\n if cnt >= 0: # in the middle of counting \n if 0 <= curr - prev <= 1: \n cnt += 1\n if x == "u": ans = max(ans, cnt)\n elif x == "a": cnt = 1\n else: cnt = -1 \n elif x == "a": cnt = 1\n prev = curr \n return ans \n```\n\nAlternative implementations\n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n ans = 0\n cnt = unique = 1\n for i in range(1, len(word)): \n if word[i-1] <= word[i]: \n cnt += 1\n if word[i-1] < word[i]: unique += 1\n else: cnt = unique = 1\n if unique == 5: ans = max(ans, cnt)\n return ans \n```\n\n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n ans = ii = 0\n unique = 1\n for i in range(1, len(word)): \n if word[i-1] > word[i]: \n ii = i \n unique = 1\n elif word[i-1] < word[i]: unique += 1\n if unique == 5: ans = max(ans, i-ii+1)\n return ans \n``` | 10 | A string is considered **beautiful** if it satisfies the following conditions:
* Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it.
* The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.).
For example, strings `"aeiou "` and `"aaaaaaeiiiioou "` are considered **beautiful**, but `"uaeio "`, `"aeoiu "`, and `"aaaeeeooo "` are **not beautiful**.
Given a string `word` consisting of English vowels, return _the **length of the longest beautiful substring** of_ `word`_. If no such substring exists, return_ `0`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** word = "aeiaaioaaaaeiiiiouuuooaauuaeiu "
**Output:** 13
**Explanation:** The longest beautiful substring in word is "aaaaeiiiiouuu " of length 13.
**Example 2:**
**Input:** word = "aeeeiiiioooauuuaeiou "
**Output:** 5
**Explanation:** The longest beautiful substring in word is "aeiou " of length 5.
**Example 3:**
**Input:** word = "a "
**Output:** 0
**Explanation:** There is no beautiful substring, so return 0.
**Constraints:**
* `1 <= word.length <= 5 * 105`
* `word` consists of characters `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. | Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i]. |
[Python3] greedy | longest-substring-of-all-vowels-in-order | 0 | 1 | \n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n vowels = "aeiou"\n ans = 0\n cnt = prev = -1 \n for i, x in enumerate(word): \n curr = vowels.index(x)\n if cnt >= 0: # in the middle of counting \n if 0 <= curr - prev <= 1: \n cnt += 1\n if x == "u": ans = max(ans, cnt)\n elif x == "a": cnt = 1\n else: cnt = -1 \n elif x == "a": cnt = 1\n prev = curr \n return ans \n```\n\nAlternative implementations\n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n ans = 0\n cnt = unique = 1\n for i in range(1, len(word)): \n if word[i-1] <= word[i]: \n cnt += 1\n if word[i-1] < word[i]: unique += 1\n else: cnt = unique = 1\n if unique == 5: ans = max(ans, cnt)\n return ans \n```\n\n```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n ans = ii = 0\n unique = 1\n for i in range(1, len(word)): \n if word[i-1] > word[i]: \n ii = i \n unique = 1\n elif word[i-1] < word[i]: unique += 1\n if unique == 5: ans = max(ans, i-ii+1)\n return ans \n``` | 10 | Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** patterns = \[ "a ", "abc ", "bc ", "d "\], word = "abc "
**Output:** 3
**Explanation:**
- "a " appears as a substring in "abc ".
- "abc " appears as a substring in "abc ".
- "bc " appears as a substring in "abc ".
- "d " does not appear as a substring in "abc ".
3 of the strings in patterns appear as a substring in word.
**Example 2:**
**Input:** patterns = \[ "a ", "b ", "c "\], word = "aaaaabbbbb "
**Output:** 2
**Explanation:**
- "a " appears as a substring in "aaaaabbbbb ".
- "b " appears as a substring in "aaaaabbbbb ".
- "c " does not appear as a substring in "aaaaabbbbb ".
2 of the strings in patterns appear as a substring in word.
**Example 3:**
**Input:** patterns = \[ "a ", "a ", "a "\], word = "ab "
**Output:** 3
**Explanation:** Each of the patterns appears as a substring in word "ab ".
**Constraints:**
* `1 <= patterns.length <= 100`
* `1 <= patterns[i].length <= 100`
* `1 <= word.length <= 100`
* `patterns[i]` and `word` consist of lowercase English letters. | Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring. |
Straightforward Python3 O(n) stack solution with explanations | longest-substring-of-all-vowels-in-order | 0 | 1 | ```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n d = {}\n d[\'a\'] = {\'a\', \'e\'}\n d[\'e\'] = {\'e\', \'i\'}\n d[\'i\'] = {\'i\', \'o\'}\n d[\'o\'] = {\'o\', \'u\'}\n d[\'u\'] = {\'u\'}\n\t\t\n res, stack = 0, []\n for c in word: \n # If stack is empty, the first char must be \'a\'\n if len(stack) == 0:\n if c == \'a\':\n stack.append(c)\n continue \n \n # If stack is NOT empty,\n # input char should be the same or subsequent to the last char in stack\n # e.g., last char in stack is \'a\', next char should be \'a\' or \'e\'\n # e.g., last char in stack is \'e\', next char should be \'e\' or \'i\'\n # ...\n # e.g., last char in stack is \'u\', next char should be \'u\'\n if c in d[stack[-1]]:\n stack.append(c)\n # If the last char in stack is eventually \'u\', \n # then we have one beautiful substring as candidate, \n # where we record and update max length of beautiful substring (res)\n if c == \'u\':\n res = max(res, len(stack))\n else:\n stack = [] if c != \'a\' else [\'a\']\n \n return res\n``` | 6 | A string is considered **beautiful** if it satisfies the following conditions:
* Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it.
* The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.).
For example, strings `"aeiou "` and `"aaaaaaeiiiioou "` are considered **beautiful**, but `"uaeio "`, `"aeoiu "`, and `"aaaeeeooo "` are **not beautiful**.
Given a string `word` consisting of English vowels, return _the **length of the longest beautiful substring** of_ `word`_. If no such substring exists, return_ `0`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** word = "aeiaaioaaaaeiiiiouuuooaauuaeiu "
**Output:** 13
**Explanation:** The longest beautiful substring in word is "aaaaeiiiiouuu " of length 13.
**Example 2:**
**Input:** word = "aeeeiiiioooauuuaeiou "
**Output:** 5
**Explanation:** The longest beautiful substring in word is "aeiou " of length 5.
**Example 3:**
**Input:** word = "a "
**Output:** 0
**Explanation:** There is no beautiful substring, so return 0.
**Constraints:**
* `1 <= word.length <= 5 * 105`
* `word` consists of characters `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. | Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i]. |
Straightforward Python3 O(n) stack solution with explanations | longest-substring-of-all-vowels-in-order | 0 | 1 | ```\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n d = {}\n d[\'a\'] = {\'a\', \'e\'}\n d[\'e\'] = {\'e\', \'i\'}\n d[\'i\'] = {\'i\', \'o\'}\n d[\'o\'] = {\'o\', \'u\'}\n d[\'u\'] = {\'u\'}\n\t\t\n res, stack = 0, []\n for c in word: \n # If stack is empty, the first char must be \'a\'\n if len(stack) == 0:\n if c == \'a\':\n stack.append(c)\n continue \n \n # If stack is NOT empty,\n # input char should be the same or subsequent to the last char in stack\n # e.g., last char in stack is \'a\', next char should be \'a\' or \'e\'\n # e.g., last char in stack is \'e\', next char should be \'e\' or \'i\'\n # ...\n # e.g., last char in stack is \'u\', next char should be \'u\'\n if c in d[stack[-1]]:\n stack.append(c)\n # If the last char in stack is eventually \'u\', \n # then we have one beautiful substring as candidate, \n # where we record and update max length of beautiful substring (res)\n if c == \'u\':\n res = max(res, len(stack))\n else:\n stack = [] if c != \'a\' else [\'a\']\n \n return res\n``` | 6 | Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** patterns = \[ "a ", "abc ", "bc ", "d "\], word = "abc "
**Output:** 3
**Explanation:**
- "a " appears as a substring in "abc ".
- "abc " appears as a substring in "abc ".
- "bc " appears as a substring in "abc ".
- "d " does not appear as a substring in "abc ".
3 of the strings in patterns appear as a substring in word.
**Example 2:**
**Input:** patterns = \[ "a ", "b ", "c "\], word = "aaaaabbbbb "
**Output:** 2
**Explanation:**
- "a " appears as a substring in "aaaaabbbbb ".
- "b " appears as a substring in "aaaaabbbbb ".
- "c " does not appear as a substring in "aaaaabbbbb ".
2 of the strings in patterns appear as a substring in word.
**Example 3:**
**Input:** patterns = \[ "a ", "a ", "a "\], word = "ab "
**Output:** 3
**Explanation:** Each of the patterns appears as a substring in word "ab ".
**Constraints:**
* `1 <= patterns.length <= 100`
* `1 <= patterns[i].length <= 100`
* `1 <= word.length <= 100`
* `patterns[i]` and `word` consist of lowercase English letters. | Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring. |
[Python3] 98% Fast Solution | longest-substring-of-all-vowels-in-order | 0 | 1 | ```\nfrom itertools import groupby\n\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n arr = groupby(word)\n \n ans = []\n \n count = 0\n \n for i , j in arr:\n ans.append([i , list(j)])\n \n for i in range(len(ans) - 4):\n if(ans[i][0] == \'a\' and ans[i + 1][0] == \'e\' and ans[i + 2][0] == \'i\' and ans[i + 3][0] == \'o\' and ans[i + 4][0] == \'u\'):\n count = max(count , len(ans[i][1]) + len(ans[i + 1][1]) + len(ans[i + 2][1]) + len(ans[i + 3][1]) + len(ans[i + 4][1])) \n \n \n return count\n``` | 9 | A string is considered **beautiful** if it satisfies the following conditions:
* Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it.
* The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.).
For example, strings `"aeiou "` and `"aaaaaaeiiiioou "` are considered **beautiful**, but `"uaeio "`, `"aeoiu "`, and `"aaaeeeooo "` are **not beautiful**.
Given a string `word` consisting of English vowels, return _the **length of the longest beautiful substring** of_ `word`_. If no such substring exists, return_ `0`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** word = "aeiaaioaaaaeiiiiouuuooaauuaeiu "
**Output:** 13
**Explanation:** The longest beautiful substring in word is "aaaaeiiiiouuu " of length 13.
**Example 2:**
**Input:** word = "aeeeiiiioooauuuaeiou "
**Output:** 5
**Explanation:** The longest beautiful substring in word is "aeiou " of length 5.
**Example 3:**
**Input:** word = "a "
**Output:** 0
**Explanation:** There is no beautiful substring, so return 0.
**Constraints:**
* `1 <= word.length <= 5 * 105`
* `word` consists of characters `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. | Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i]. |
[Python3] 98% Fast Solution | longest-substring-of-all-vowels-in-order | 0 | 1 | ```\nfrom itertools import groupby\n\nclass Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n arr = groupby(word)\n \n ans = []\n \n count = 0\n \n for i , j in arr:\n ans.append([i , list(j)])\n \n for i in range(len(ans) - 4):\n if(ans[i][0] == \'a\' and ans[i + 1][0] == \'e\' and ans[i + 2][0] == \'i\' and ans[i + 3][0] == \'o\' and ans[i + 4][0] == \'u\'):\n count = max(count , len(ans[i][1]) + len(ans[i + 1][1]) + len(ans[i + 2][1]) + len(ans[i + 3][1]) + len(ans[i + 4][1])) \n \n \n return count\n``` | 9 | Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** patterns = \[ "a ", "abc ", "bc ", "d "\], word = "abc "
**Output:** 3
**Explanation:**
- "a " appears as a substring in "abc ".
- "abc " appears as a substring in "abc ".
- "bc " appears as a substring in "abc ".
- "d " does not appear as a substring in "abc ".
3 of the strings in patterns appear as a substring in word.
**Example 2:**
**Input:** patterns = \[ "a ", "b ", "c "\], word = "aaaaabbbbb "
**Output:** 2
**Explanation:**
- "a " appears as a substring in "aaaaabbbbb ".
- "b " appears as a substring in "aaaaabbbbb ".
- "c " does not appear as a substring in "aaaaabbbbb ".
2 of the strings in patterns appear as a substring in word.
**Example 3:**
**Input:** patterns = \[ "a ", "a ", "a "\], word = "ab "
**Output:** 3
**Explanation:** Each of the patterns appears as a substring in word "ab ".
**Constraints:**
* `1 <= patterns.length <= 100`
* `1 <= patterns[i].length <= 100`
* `1 <= word.length <= 100`
* `patterns[i]` and `word` consist of lowercase English letters. | Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring. |
Python soln | longest-substring-of-all-vowels-in-order | 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 longestBeautifulSubstring(self, word: str) -> int:\n n=len(word)\n maxi=0\n i=0\n j=0\n\n while j<n:\n if j<n-1 and word[j+1]>=word[j]:\n j+=1\n else:\n if word[j]==\'u\' and len(set(word[i:j+1]))==5:\n maxi=max(maxi,j-i+1)\n i=j+1\n j=j+1\n\n return maxi\n\n\n``` | 0 | A string is considered **beautiful** if it satisfies the following conditions:
* Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it.
* The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.).
For example, strings `"aeiou "` and `"aaaaaaeiiiioou "` are considered **beautiful**, but `"uaeio "`, `"aeoiu "`, and `"aaaeeeooo "` are **not beautiful**.
Given a string `word` consisting of English vowels, return _the **length of the longest beautiful substring** of_ `word`_. If no such substring exists, return_ `0`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** word = "aeiaaioaaaaeiiiiouuuooaauuaeiu "
**Output:** 13
**Explanation:** The longest beautiful substring in word is "aaaaeiiiiouuu " of length 13.
**Example 2:**
**Input:** word = "aeeeiiiioooauuuaeiou "
**Output:** 5
**Explanation:** The longest beautiful substring in word is "aeiou " of length 5.
**Example 3:**
**Input:** word = "a "
**Output:** 0
**Explanation:** There is no beautiful substring, so return 0.
**Constraints:**
* `1 <= word.length <= 5 * 105`
* `word` consists of characters `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. | Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i]. |
Python soln | longest-substring-of-all-vowels-in-order | 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 longestBeautifulSubstring(self, word: str) -> int:\n n=len(word)\n maxi=0\n i=0\n j=0\n\n while j<n:\n if j<n-1 and word[j+1]>=word[j]:\n j+=1\n else:\n if word[j]==\'u\' and len(set(word[i:j+1]))==5:\n maxi=max(maxi,j-i+1)\n i=j+1\n j=j+1\n\n return maxi\n\n\n``` | 0 | Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** patterns = \[ "a ", "abc ", "bc ", "d "\], word = "abc "
**Output:** 3
**Explanation:**
- "a " appears as a substring in "abc ".
- "abc " appears as a substring in "abc ".
- "bc " appears as a substring in "abc ".
- "d " does not appear as a substring in "abc ".
3 of the strings in patterns appear as a substring in word.
**Example 2:**
**Input:** patterns = \[ "a ", "b ", "c "\], word = "aaaaabbbbb "
**Output:** 2
**Explanation:**
- "a " appears as a substring in "aaaaabbbbb ".
- "b " appears as a substring in "aaaaabbbbb ".
- "c " does not appear as a substring in "aaaaabbbbb ".
2 of the strings in patterns appear as a substring in word.
**Example 3:**
**Input:** patterns = \[ "a ", "a ", "a "\], word = "ab "
**Output:** 3
**Explanation:** Each of the patterns appears as a substring in word "ab ".
**Constraints:**
* `1 <= patterns.length <= 100`
* `1 <= patterns[i].length <= 100`
* `1 <= word.length <= 100`
* `patterns[i]` and `word` consist of lowercase English letters. | Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring. |
O(n) without SET or HASMAP | longest-substring-of-all-vowels-in-order | 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 longestBeautifulSubstring(self, word: str) -> int:\n vowel=["a","e","i","o","u"]\n windowstart=0\n longestSub=0\n curCount=0\n curVowel=[]\n for windowend in range(0,len(word)):\n if len(curVowel)==0:\n if word[windowend]==vowel[0]:\n curVowel.append(word[windowend])\n curCount+=1\n windowstart=windowend\n else:\n windowstart=windowend \n\n else:\n if word[windowend] not in curVowel and word[windowend]==vowel[len(curVowel)]: #[a,e] i\n curVowel.append(word[windowend])\n curCount+=1\n elif (word[windowend] in curVowel and word[windowend]!=curVowel[-1]) or (word[windowend] not in curVowel and word[windowend]!=vowel[len(curVowel)]): \n curCount=0\n curVowel=[]\n if word[windowend]=="a":\n curVowel.append("a")\n windowstart=windowend\n #print("yes",windowend,windowstart)\n if len(curVowel)==len(vowel):\n longestSub=max(longestSub,windowend-windowstart+1)\n return longestSub \n\n\n \n\n #the last repeating character\n \n\n\n\n\n\n\n\n\n\n\n``` | 0 | A string is considered **beautiful** if it satisfies the following conditions:
* Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it.
* The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.).
For example, strings `"aeiou "` and `"aaaaaaeiiiioou "` are considered **beautiful**, but `"uaeio "`, `"aeoiu "`, and `"aaaeeeooo "` are **not beautiful**.
Given a string `word` consisting of English vowels, return _the **length of the longest beautiful substring** of_ `word`_. If no such substring exists, return_ `0`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** word = "aeiaaioaaaaeiiiiouuuooaauuaeiu "
**Output:** 13
**Explanation:** The longest beautiful substring in word is "aaaaeiiiiouuu " of length 13.
**Example 2:**
**Input:** word = "aeeeiiiioooauuuaeiou "
**Output:** 5
**Explanation:** The longest beautiful substring in word is "aeiou " of length 5.
**Example 3:**
**Input:** word = "a "
**Output:** 0
**Explanation:** There is no beautiful substring, so return 0.
**Constraints:**
* `1 <= word.length <= 5 * 105`
* `word` consists of characters `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. | Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i]. |
O(n) without SET or HASMAP | longest-substring-of-all-vowels-in-order | 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 longestBeautifulSubstring(self, word: str) -> int:\n vowel=["a","e","i","o","u"]\n windowstart=0\n longestSub=0\n curCount=0\n curVowel=[]\n for windowend in range(0,len(word)):\n if len(curVowel)==0:\n if word[windowend]==vowel[0]:\n curVowel.append(word[windowend])\n curCount+=1\n windowstart=windowend\n else:\n windowstart=windowend \n\n else:\n if word[windowend] not in curVowel and word[windowend]==vowel[len(curVowel)]: #[a,e] i\n curVowel.append(word[windowend])\n curCount+=1\n elif (word[windowend] in curVowel and word[windowend]!=curVowel[-1]) or (word[windowend] not in curVowel and word[windowend]!=vowel[len(curVowel)]): \n curCount=0\n curVowel=[]\n if word[windowend]=="a":\n curVowel.append("a")\n windowstart=windowend\n #print("yes",windowend,windowstart)\n if len(curVowel)==len(vowel):\n longestSub=max(longestSub,windowend-windowstart+1)\n return longestSub \n\n\n \n\n #the last repeating character\n \n\n\n\n\n\n\n\n\n\n\n``` | 0 | Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** patterns = \[ "a ", "abc ", "bc ", "d "\], word = "abc "
**Output:** 3
**Explanation:**
- "a " appears as a substring in "abc ".
- "abc " appears as a substring in "abc ".
- "bc " appears as a substring in "abc ".
- "d " does not appear as a substring in "abc ".
3 of the strings in patterns appear as a substring in word.
**Example 2:**
**Input:** patterns = \[ "a ", "b ", "c "\], word = "aaaaabbbbb "
**Output:** 2
**Explanation:**
- "a " appears as a substring in "aaaaabbbbb ".
- "b " appears as a substring in "aaaaabbbbb ".
- "c " does not appear as a substring in "aaaaabbbbb ".
2 of the strings in patterns appear as a substring in word.
**Example 3:**
**Input:** patterns = \[ "a ", "a ", "a "\], word = "ab "
**Output:** 3
**Explanation:** Each of the patterns appears as a substring in word "ab ".
**Constraints:**
* `1 <= patterns.length <= 100`
* `1 <= patterns[i].length <= 100`
* `1 <= word.length <= 100`
* `patterns[i]` and `word` consist of lowercase English letters. | Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring. |
Sorting and Two Passes in Python | maximum-building-height | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nThe first step is to sort the restrictions according to their positions. \nThe first pass begins from the rightmost to the leftmost for setting new height restriction of i according to the height restriction of its right parter (i+1).\nThe second pass begins from the leftmost to the rightmost for finding the answer. The maximum height between restrictions i and i+1 is determined by the function `max_point()` in my implmenetation. A new height restrictions to the i+1 building will also be updated at the same time. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nSorting: $$O(n \\log n)$$\nTwo passes: $$O(n)$$ \n$$n$$ is the length of `restrictions`\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ in place. \n\n# Code\n```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n def max_point(x1, h1, x2, h2):\n w, d = x2 - x1, abs(h2 - h1)\n h = w - ((max(0, w-d) + 1) // 2)\n return min(h1, h2) + h\n\n restrictions = sorted(restrictions + [[1, 0], [n, n+1]])\n for i in range(len(restrictions) - 2, -1, -1):\n if restrictions[i][1] > restrictions[i+1][1]:\n w = restrictions[i+1][0] - restrictions[i][0]\n restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1] + w)\n ans = 0\n for i in range(len(restrictions)-1):\n h = max_point(*restrictions[i], *restrictions[i+1])\n restrictions[i+1][1] = min(restrictions[i+1][1], h)\n ans = max(ans, h)\n return ans\n\n \n``` | 0 | You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`.
However, there are city restrictions on the heights of the new buildings:
* The height of each building must be a non-negative integer.
* The height of the first building **must** be `0`.
* The height difference between any two adjacent buildings **cannot exceed** `1`.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where `restrictions[i] = [idi, maxHeighti]` indicates that building `idi` must have a height **less than or equal to** `maxHeighti`.
It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`.
Return _the **maximum possible height** of the **tallest** building_.
**Example 1:**
**Input:** n = 5, restrictions = \[\[2,1\],\[4,1\]\]
**Output:** 2
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,1,2\], and the tallest building has a height of 2.
**Example 2:**
**Input:** n = 6, restrictions = \[\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,4,5\], and the tallest building has a height of 5.
**Example 3:**
**Input:** n = 10, restrictions = \[\[5,3\],\[2,5\],\[7,4\],\[10,3\]\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,3,4,4,5,4,3\], and the tallest building has a height of 5.
**Constraints:**
* `2 <= n <= 109`
* `0 <= restrictions.length <= min(n - 1, 105)`
* `2 <= idi <= n`
* `idi` is **unique**.
* `0 <= maxHeighti <= 109` | The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance. |
Sorting and Two Passes in Python | maximum-building-height | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nThe first step is to sort the restrictions according to their positions. \nThe first pass begins from the rightmost to the leftmost for setting new height restriction of i according to the height restriction of its right parter (i+1).\nThe second pass begins from the leftmost to the rightmost for finding the answer. The maximum height between restrictions i and i+1 is determined by the function `max_point()` in my implmenetation. A new height restrictions to the i+1 building will also be updated at the same time. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nSorting: $$O(n \\log n)$$\nTwo passes: $$O(n)$$ \n$$n$$ is the length of `restrictions`\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ in place. \n\n# Code\n```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n def max_point(x1, h1, x2, h2):\n w, d = x2 - x1, abs(h2 - h1)\n h = w - ((max(0, w-d) + 1) // 2)\n return min(h1, h2) + h\n\n restrictions = sorted(restrictions + [[1, 0], [n, n+1]])\n for i in range(len(restrictions) - 2, -1, -1):\n if restrictions[i][1] > restrictions[i+1][1]:\n w = restrictions[i+1][0] - restrictions[i][0]\n restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1] + w)\n ans = 0\n for i in range(len(restrictions)-1):\n h = max_point(*restrictions[i], *restrictions[i+1])\n restrictions[i+1][1] = min(restrictions[i+1][1], h)\n ans = max(ans, h)\n return ans\n\n \n``` | 0 | You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1 <= i < nums.length - 1`, `(nums[i-1] + nums[i+1]) / 2` is **not** equal to `nums[i]`.
Return _**any** rearrangement of_ `nums` _that meets the requirements_.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** \[1,2,4,5,3\]
**Explanation:**
When i=1, nums\[i\] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.
When i=2, nums\[i\] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.
When i=3, nums\[i\] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.
**Example 2:**
**Input:** nums = \[6,2,0,9,7\]
**Output:** \[9,7,6,2,0\]
**Explanation:**
When i=1, nums\[i\] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.
When i=2, nums\[i\] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.
When i=3, nums\[i\] = 2, and the average of its neighbors is (6+0) / 2 = 3.
**Constraints:**
* `3 <= nums.length <= 105`
* `0 <= nums[i] <= 105` | Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right. |
Python || sort, greedy || O(m log m) | maximum-building-height | 0 | 1 | 1. Add `[1,0]` to `restrictions`, then sort `restrictions` by index in ascending order.\n2. We will do the same procedure twice, forward and backward. The procedure is as following:\n2-1. Move to `(idx_2, res_2)` and check previous `(idx_1, res_1)`. \n2-2. Let `steps = abs(idx_1-idx_2)`. Starting from `idx_1`, the maximal height we can reach at \'idx_2\' would be `res_1 + steps`.\n2-3. So if `res_2 > res_1 + steps`, replace `res_2` by `res_1 + steps`.\n3. After that, we\'re ready to find the answer. \nGiven two adjacent restrictions, `(idx_1, res_1)` and `(idx_2, res_2)`, suppose the maximal height between them(inclusive) is `h`.\n`(h-res_1) + (h-res_2) = steps`, which implies `h = (steps+res_1+res_2) // 2`.\nAnd don\'t forget the last segment between `restrictions[-1][0]` and `n`.\n```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n restrictions = [[1, 0]] + restrictions\n restrictions.sort()\n m = len(restrictions)\n \n # from 1 to n\n for i, (idx_2, res_2) in enumerate(restrictions[1:], start=1):\n idx_1, res_1 = restrictions[i-1]\n steps = idx_2 - idx_1\n if res_2 - res_1 > steps:\n restrictions[i][1] = res_1 + steps\n \n # from n to 1\n for i, (idx_2, res_2) in enumerate(restrictions[m-2:0:-1]):\n idx_1, res_1 = restrictions[m-i-1]\n steps = idx_1 - idx_2\n if res_2 - res_1 > steps:\n restrictions[m-2-i][1] = res_1 + steps\n \n # find maximal height\n idx, res = restrictions[-1]\n ans = res + (n-idx)\n for i, (idx_2, res_2) in enumerate(restrictions[1:], start=1):\n idx_1, res_1 = restrictions[i-1]\n steps = idx_2 - idx_1\n ans = max(ans, (steps + res_1 + res_2) // 2)\n return ans | 0 | You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`.
However, there are city restrictions on the heights of the new buildings:
* The height of each building must be a non-negative integer.
* The height of the first building **must** be `0`.
* The height difference between any two adjacent buildings **cannot exceed** `1`.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where `restrictions[i] = [idi, maxHeighti]` indicates that building `idi` must have a height **less than or equal to** `maxHeighti`.
It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`.
Return _the **maximum possible height** of the **tallest** building_.
**Example 1:**
**Input:** n = 5, restrictions = \[\[2,1\],\[4,1\]\]
**Output:** 2
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,1,2\], and the tallest building has a height of 2.
**Example 2:**
**Input:** n = 6, restrictions = \[\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,4,5\], and the tallest building has a height of 5.
**Example 3:**
**Input:** n = 10, restrictions = \[\[5,3\],\[2,5\],\[7,4\],\[10,3\]\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,3,4,4,5,4,3\], and the tallest building has a height of 5.
**Constraints:**
* `2 <= n <= 109`
* `0 <= restrictions.length <= min(n - 1, 105)`
* `2 <= idi <= n`
* `idi` is **unique**.
* `0 <= maxHeighti <= 109` | The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance. |
Python || sort, greedy || O(m log m) | maximum-building-height | 0 | 1 | 1. Add `[1,0]` to `restrictions`, then sort `restrictions` by index in ascending order.\n2. We will do the same procedure twice, forward and backward. The procedure is as following:\n2-1. Move to `(idx_2, res_2)` and check previous `(idx_1, res_1)`. \n2-2. Let `steps = abs(idx_1-idx_2)`. Starting from `idx_1`, the maximal height we can reach at \'idx_2\' would be `res_1 + steps`.\n2-3. So if `res_2 > res_1 + steps`, replace `res_2` by `res_1 + steps`.\n3. After that, we\'re ready to find the answer. \nGiven two adjacent restrictions, `(idx_1, res_1)` and `(idx_2, res_2)`, suppose the maximal height between them(inclusive) is `h`.\n`(h-res_1) + (h-res_2) = steps`, which implies `h = (steps+res_1+res_2) // 2`.\nAnd don\'t forget the last segment between `restrictions[-1][0]` and `n`.\n```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n restrictions = [[1, 0]] + restrictions\n restrictions.sort()\n m = len(restrictions)\n \n # from 1 to n\n for i, (idx_2, res_2) in enumerate(restrictions[1:], start=1):\n idx_1, res_1 = restrictions[i-1]\n steps = idx_2 - idx_1\n if res_2 - res_1 > steps:\n restrictions[i][1] = res_1 + steps\n \n # from n to 1\n for i, (idx_2, res_2) in enumerate(restrictions[m-2:0:-1]):\n idx_1, res_1 = restrictions[m-i-1]\n steps = idx_1 - idx_2\n if res_2 - res_1 > steps:\n restrictions[m-2-i][1] = res_1 + steps\n \n # find maximal height\n idx, res = restrictions[-1]\n ans = res + (n-idx)\n for i, (idx_2, res_2) in enumerate(restrictions[1:], start=1):\n idx_1, res_1 = restrictions[i-1]\n steps = idx_2 - idx_1\n ans = max(ans, (steps + res_1 + res_2) // 2)\n return ans | 0 | You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1 <= i < nums.length - 1`, `(nums[i-1] + nums[i+1]) / 2` is **not** equal to `nums[i]`.
Return _**any** rearrangement of_ `nums` _that meets the requirements_.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** \[1,2,4,5,3\]
**Explanation:**
When i=1, nums\[i\] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.
When i=2, nums\[i\] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.
When i=3, nums\[i\] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.
**Example 2:**
**Input:** nums = \[6,2,0,9,7\]
**Output:** \[9,7,6,2,0\]
**Explanation:**
When i=1, nums\[i\] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.
When i=2, nums\[i\] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.
When i=3, nums\[i\] = 2, and the average of its neighbors is (6+0) / 2 = 3.
**Constraints:**
* `3 <= nums.length <= 105`
* `0 <= nums[i] <= 105` | Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right. |
BS ON ANSWER | maximum-building-height | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def maxBuilding(self, n: int, rt: List[List[int]]) -> int:\n rt.append([0,-1])\n rt.append([n,float("inf")])\n rt.sort()\n n=len(rt)\n for i in range(1,n):\n rt[i][1]=min(rt[i][0]-rt[i-1][0]+rt[i-1][1],rt[i][1])\n for i in range(n-2,-1,-1):\n if rt[i+1][-1]<rt[i][-1]:\n req=rt[i][-1]-rt[i+1][-1]\n has=rt[i+1][0]-rt[i][0]\n if has<req:\n rt[i][1]-=(req-has)\n lo=0\n hi=10**9+1\n ans=-1\n while lo<=hi:\n mid=(lo+hi)//2\n f=False\n for i in range(1,len(rt)):\n inc=max(mid-rt[i-1][1],0)\n dec=max(mid-rt[i][1],0)\n\n if inc +dec<=rt[i][0]-rt[i-1][0]:\n f=True\n break\n if f:\n ans=mid\n lo=mid+1\n else:\n hi=mid-1\n return ans\n\n``` | 0 | You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`.
However, there are city restrictions on the heights of the new buildings:
* The height of each building must be a non-negative integer.
* The height of the first building **must** be `0`.
* The height difference between any two adjacent buildings **cannot exceed** `1`.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where `restrictions[i] = [idi, maxHeighti]` indicates that building `idi` must have a height **less than or equal to** `maxHeighti`.
It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`.
Return _the **maximum possible height** of the **tallest** building_.
**Example 1:**
**Input:** n = 5, restrictions = \[\[2,1\],\[4,1\]\]
**Output:** 2
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,1,2\], and the tallest building has a height of 2.
**Example 2:**
**Input:** n = 6, restrictions = \[\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,4,5\], and the tallest building has a height of 5.
**Example 3:**
**Input:** n = 10, restrictions = \[\[5,3\],\[2,5\],\[7,4\],\[10,3\]\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,3,4,4,5,4,3\], and the tallest building has a height of 5.
**Constraints:**
* `2 <= n <= 109`
* `0 <= restrictions.length <= min(n - 1, 105)`
* `2 <= idi <= n`
* `idi` is **unique**.
* `0 <= maxHeighti <= 109` | The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance. |
BS ON ANSWER | maximum-building-height | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def maxBuilding(self, n: int, rt: List[List[int]]) -> int:\n rt.append([0,-1])\n rt.append([n,float("inf")])\n rt.sort()\n n=len(rt)\n for i in range(1,n):\n rt[i][1]=min(rt[i][0]-rt[i-1][0]+rt[i-1][1],rt[i][1])\n for i in range(n-2,-1,-1):\n if rt[i+1][-1]<rt[i][-1]:\n req=rt[i][-1]-rt[i+1][-1]\n has=rt[i+1][0]-rt[i][0]\n if has<req:\n rt[i][1]-=(req-has)\n lo=0\n hi=10**9+1\n ans=-1\n while lo<=hi:\n mid=(lo+hi)//2\n f=False\n for i in range(1,len(rt)):\n inc=max(mid-rt[i-1][1],0)\n dec=max(mid-rt[i][1],0)\n\n if inc +dec<=rt[i][0]-rt[i-1][0]:\n f=True\n break\n if f:\n ans=mid\n lo=mid+1\n else:\n hi=mid-1\n return ans\n\n``` | 0 | You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1 <= i < nums.length - 1`, `(nums[i-1] + nums[i+1]) / 2` is **not** equal to `nums[i]`.
Return _**any** rearrangement of_ `nums` _that meets the requirements_.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** \[1,2,4,5,3\]
**Explanation:**
When i=1, nums\[i\] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.
When i=2, nums\[i\] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.
When i=3, nums\[i\] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.
**Example 2:**
**Input:** nums = \[6,2,0,9,7\]
**Output:** \[9,7,6,2,0\]
**Explanation:**
When i=1, nums\[i\] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.
When i=2, nums\[i\] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.
When i=3, nums\[i\] = 2, and the average of its neighbors is (6+0) / 2 = 3.
**Constraints:**
* `3 <= nums.length <= 105`
* `0 <= nums[i] <= 105` | Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right. |
Python (Simple Maths) | maximum-building-height | 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 maxBuilding(self, n, restrictions):\n restrictions.extend([[1,0],[n,n-1]])\n restrictions.sort()\n m = len(restrictions)\n\n for i in range(1,m):\n restrictions[i][1] = min(restrictions[i][1],restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0])\n\n for i in range(m-2,-1,-1):\n restrictions[i][1] = min(restrictions[i][1],restrictions[i+1][1] + restrictions[i+1][0] - restrictions[i][0])\n\n max_val = 0\n\n for i in range(1,m):\n l,h1 = restrictions[i-1]\n r,h2 = restrictions[i]\n max_val = max(max_val,max(h1,h2) + (r-l-abs(h1-h2))//2)\n\n return max_val\n\n``` | 0 | You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`.
However, there are city restrictions on the heights of the new buildings:
* The height of each building must be a non-negative integer.
* The height of the first building **must** be `0`.
* The height difference between any two adjacent buildings **cannot exceed** `1`.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where `restrictions[i] = [idi, maxHeighti]` indicates that building `idi` must have a height **less than or equal to** `maxHeighti`.
It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`.
Return _the **maximum possible height** of the **tallest** building_.
**Example 1:**
**Input:** n = 5, restrictions = \[\[2,1\],\[4,1\]\]
**Output:** 2
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,1,2\], and the tallest building has a height of 2.
**Example 2:**
**Input:** n = 6, restrictions = \[\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,4,5\], and the tallest building has a height of 5.
**Example 3:**
**Input:** n = 10, restrictions = \[\[5,3\],\[2,5\],\[7,4\],\[10,3\]\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,3,4,4,5,4,3\], and the tallest building has a height of 5.
**Constraints:**
* `2 <= n <= 109`
* `0 <= restrictions.length <= min(n - 1, 105)`
* `2 <= idi <= n`
* `idi` is **unique**.
* `0 <= maxHeighti <= 109` | The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance. |
Python (Simple Maths) | maximum-building-height | 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 maxBuilding(self, n, restrictions):\n restrictions.extend([[1,0],[n,n-1]])\n restrictions.sort()\n m = len(restrictions)\n\n for i in range(1,m):\n restrictions[i][1] = min(restrictions[i][1],restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0])\n\n for i in range(m-2,-1,-1):\n restrictions[i][1] = min(restrictions[i][1],restrictions[i+1][1] + restrictions[i+1][0] - restrictions[i][0])\n\n max_val = 0\n\n for i in range(1,m):\n l,h1 = restrictions[i-1]\n r,h2 = restrictions[i]\n max_val = max(max_val,max(h1,h2) + (r-l-abs(h1-h2))//2)\n\n return max_val\n\n``` | 0 | You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1 <= i < nums.length - 1`, `(nums[i-1] + nums[i+1]) / 2` is **not** equal to `nums[i]`.
Return _**any** rearrangement of_ `nums` _that meets the requirements_.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** \[1,2,4,5,3\]
**Explanation:**
When i=1, nums\[i\] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.
When i=2, nums\[i\] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.
When i=3, nums\[i\] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.
**Example 2:**
**Input:** nums = \[6,2,0,9,7\]
**Output:** \[9,7,6,2,0\]
**Explanation:**
When i=1, nums\[i\] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.
When i=2, nums\[i\] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.
When i=3, nums\[i\] = 2, and the average of its neighbors is (6+0) / 2 = 3.
**Constraints:**
* `3 <= nums.length <= 105`
* `0 <= nums[i] <= 105` | Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right. |
Python 6-lines | maximum-building-height | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nFirst, sort restrictions with respect to first limiting the height of buildings when we traverse line from left to right.\n\nThen, traverse through array and store rightmost restriction in every point. In every comparison, leftmost and rightmost restriction line\'s intersection point will be the maximum allowed height at that point. \n\nOne thing should be considered is intersection points have to be in the [0,n] range.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe update ans when we encounter a point which allows longer building. \n\n# Complexity\n- Time complexity: O(nlogn)\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 maxBuilding(self, n: int, re: List[List[int]]) -> int:\n re.sort(key=lambda i:i[0]+i[1])\n ans, b = 0, [1,0]\n for r in re:\n ans = max(ans,(min(2*n-b[0]+b[1],r[0]+r[1])-(b[0]-b[1]))//2)\n if b[0]-b[1] < r[0]-r[1]: b = [r[0],r[1]]\n return max(ans,n-b[0]+b[1])\n``` | 0 | You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`.
However, there are city restrictions on the heights of the new buildings:
* The height of each building must be a non-negative integer.
* The height of the first building **must** be `0`.
* The height difference between any two adjacent buildings **cannot exceed** `1`.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where `restrictions[i] = [idi, maxHeighti]` indicates that building `idi` must have a height **less than or equal to** `maxHeighti`.
It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`.
Return _the **maximum possible height** of the **tallest** building_.
**Example 1:**
**Input:** n = 5, restrictions = \[\[2,1\],\[4,1\]\]
**Output:** 2
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,1,2\], and the tallest building has a height of 2.
**Example 2:**
**Input:** n = 6, restrictions = \[\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,4,5\], and the tallest building has a height of 5.
**Example 3:**
**Input:** n = 10, restrictions = \[\[5,3\],\[2,5\],\[7,4\],\[10,3\]\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,3,4,4,5,4,3\], and the tallest building has a height of 5.
**Constraints:**
* `2 <= n <= 109`
* `0 <= restrictions.length <= min(n - 1, 105)`
* `2 <= idi <= n`
* `idi` is **unique**.
* `0 <= maxHeighti <= 109` | The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance. |
Python 6-lines | maximum-building-height | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nFirst, sort restrictions with respect to first limiting the height of buildings when we traverse line from left to right.\n\nThen, traverse through array and store rightmost restriction in every point. In every comparison, leftmost and rightmost restriction line\'s intersection point will be the maximum allowed height at that point. \n\nOne thing should be considered is intersection points have to be in the [0,n] range.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe update ans when we encounter a point which allows longer building. \n\n# Complexity\n- Time complexity: O(nlogn)\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 maxBuilding(self, n: int, re: List[List[int]]) -> int:\n re.sort(key=lambda i:i[0]+i[1])\n ans, b = 0, [1,0]\n for r in re:\n ans = max(ans,(min(2*n-b[0]+b[1],r[0]+r[1])-(b[0]-b[1]))//2)\n if b[0]-b[1] < r[0]-r[1]: b = [r[0],r[1]]\n return max(ans,n-b[0]+b[1])\n``` | 0 | You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1 <= i < nums.length - 1`, `(nums[i-1] + nums[i+1]) / 2` is **not** equal to `nums[i]`.
Return _**any** rearrangement of_ `nums` _that meets the requirements_.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** \[1,2,4,5,3\]
**Explanation:**
When i=1, nums\[i\] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.
When i=2, nums\[i\] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.
When i=3, nums\[i\] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.
**Example 2:**
**Input:** nums = \[6,2,0,9,7\]
**Output:** \[9,7,6,2,0\]
**Explanation:**
When i=1, nums\[i\] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.
When i=2, nums\[i\] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.
When i=3, nums\[i\] = 2, and the average of its neighbors is (6+0) / 2 = 3.
**Constraints:**
* `3 <= nums.length <= 105`
* `0 <= nums[i] <= 105` | Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right. |
[Python3] greedy | maximum-building-height | 0 | 1 | \n```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n restrictions.extend([[1, 0], [n, n-1]])\n restrictions.sort()\n \n for i in reversed(range(len(restrictions)-1)): \n restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1] + restrictions[i+1][0] - restrictions[i][0])\n \n ans = 0 \n for i in range(1, len(restrictions)): \n restrictions[i][1] = min(restrictions[i][1], restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0])\n ans = max(ans, (restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0] + restrictions[i][1])//2)\n return ans \n``` | 4 | You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`.
However, there are city restrictions on the heights of the new buildings:
* The height of each building must be a non-negative integer.
* The height of the first building **must** be `0`.
* The height difference between any two adjacent buildings **cannot exceed** `1`.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where `restrictions[i] = [idi, maxHeighti]` indicates that building `idi` must have a height **less than or equal to** `maxHeighti`.
It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`.
Return _the **maximum possible height** of the **tallest** building_.
**Example 1:**
**Input:** n = 5, restrictions = \[\[2,1\],\[4,1\]\]
**Output:** 2
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,1,2\], and the tallest building has a height of 2.
**Example 2:**
**Input:** n = 6, restrictions = \[\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,4,5\], and the tallest building has a height of 5.
**Example 3:**
**Input:** n = 10, restrictions = \[\[5,3\],\[2,5\],\[7,4\],\[10,3\]\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,3,4,4,5,4,3\], and the tallest building has a height of 5.
**Constraints:**
* `2 <= n <= 109`
* `0 <= restrictions.length <= min(n - 1, 105)`
* `2 <= idi <= n`
* `idi` is **unique**.
* `0 <= maxHeighti <= 109` | The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance. |
[Python3] greedy | maximum-building-height | 0 | 1 | \n```\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n restrictions.extend([[1, 0], [n, n-1]])\n restrictions.sort()\n \n for i in reversed(range(len(restrictions)-1)): \n restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1] + restrictions[i+1][0] - restrictions[i][0])\n \n ans = 0 \n for i in range(1, len(restrictions)): \n restrictions[i][1] = min(restrictions[i][1], restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0])\n ans = max(ans, (restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0] + restrictions[i][1])//2)\n return ans \n``` | 4 | You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1 <= i < nums.length - 1`, `(nums[i-1] + nums[i+1]) / 2` is **not** equal to `nums[i]`.
Return _**any** rearrangement of_ `nums` _that meets the requirements_.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** \[1,2,4,5,3\]
**Explanation:**
When i=1, nums\[i\] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.
When i=2, nums\[i\] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.
When i=3, nums\[i\] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.
**Example 2:**
**Input:** nums = \[6,2,0,9,7\]
**Output:** \[9,7,6,2,0\]
**Explanation:**
When i=1, nums\[i\] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.
When i=2, nums\[i\] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.
When i=3, nums\[i\] = 2, and the average of its neighbors is (6+0) / 2 = 3.
**Constraints:**
* `3 <= nums.length <= 105`
* `0 <= nums[i] <= 105` | Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right. |
TC: O(N) SC: O(1) Greedy Approach Explained Python | maximum-building-height | 0 | 1 | For each building you want to find the most constraining height either on left or right\nm = len(restrictions) <= 10^5 so O(m^2) is too slow\nBut we can find biggest restriction on left for each element is one loop, and\nfind the biggest restriction on right for each element in one loop aswell\n\nlet curr biggest restriction on left be (c_b,c_h) where c_b is building location and c_h is the height of that building\nif restriction[i][1] < i - c_b + c_h then (i, restriction[i][1]) is the new biggest restriction on left\nif restriction[i][1] > i - c_b + c_h then apply the restriction to building i\n\nBut you dont want to calulcate restriction for every building because n <= 10^9\nSo you just work with the intervals in restrictions\nand max height in that interval is the intersection of two lines:\ny1 = (x - left_building_location) + height_left_building\ny2 = (right_building_location - x) + height_right_building\n\n```\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n restrictions += [[1, 0]]\n restrictions.sort() #sort by building number\n\n #if last building is not in restriction add it\n #and its height must be <= n-1 because first building is 0\n if restrictions[-1][0] != n: restrictions.append([n, n-1])\n \n c = 1; c_h = 0\n for i in range(len(restrictions)):\n b,h = restrictions[i]\n\n if (b-c) + c_h < h:\n restrictions[i][1] = (b-c) + c_h\n else:\n c = b; c_h = h \n \n c, c_h = restrictions[-1]\n for i in range(len(restrictions)-1, -1, -1):\n b,h = restrictions[i]\n\n if (c-b) + c_h < h:\n restrictions[i][1] = (c-b) + c_h\n else:\n c = b; c_h = h \n \n ans = 0\n for i in range(len(restrictions) - 1):\n left, left_h = restrictions[i]\n right, right_h = restrictions[i+1]\n\n #y1 = (x - left) + left_h\n #y2 = (rigth - x) + right_h, their intersection is the max_h in that interval\n # x - left + l_h = right - x + r_h\n # x = (right + left + r_h - l_h)/2\n # y = (right + left + r_h - l_h)/2 - left + l_h\n location = (right + left + right_h - left_h)//2 #building_id must be integer\n height = location - left + left_h\n ans = max(ans, height)\n\n return ans\n``` | 0 | You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`.
However, there are city restrictions on the heights of the new buildings:
* The height of each building must be a non-negative integer.
* The height of the first building **must** be `0`.
* The height difference between any two adjacent buildings **cannot exceed** `1`.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where `restrictions[i] = [idi, maxHeighti]` indicates that building `idi` must have a height **less than or equal to** `maxHeighti`.
It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`.
Return _the **maximum possible height** of the **tallest** building_.
**Example 1:**
**Input:** n = 5, restrictions = \[\[2,1\],\[4,1\]\]
**Output:** 2
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,1,2\], and the tallest building has a height of 2.
**Example 2:**
**Input:** n = 6, restrictions = \[\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,4,5\], and the tallest building has a height of 5.
**Example 3:**
**Input:** n = 10, restrictions = \[\[5,3\],\[2,5\],\[7,4\],\[10,3\]\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,3,4,4,5,4,3\], and the tallest building has a height of 5.
**Constraints:**
* `2 <= n <= 109`
* `0 <= restrictions.length <= min(n - 1, 105)`
* `2 <= idi <= n`
* `idi` is **unique**.
* `0 <= maxHeighti <= 109` | The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance. |
TC: O(N) SC: O(1) Greedy Approach Explained Python | maximum-building-height | 0 | 1 | For each building you want to find the most constraining height either on left or right\nm = len(restrictions) <= 10^5 so O(m^2) is too slow\nBut we can find biggest restriction on left for each element is one loop, and\nfind the biggest restriction on right for each element in one loop aswell\n\nlet curr biggest restriction on left be (c_b,c_h) where c_b is building location and c_h is the height of that building\nif restriction[i][1] < i - c_b + c_h then (i, restriction[i][1]) is the new biggest restriction on left\nif restriction[i][1] > i - c_b + c_h then apply the restriction to building i\n\nBut you dont want to calulcate restriction for every building because n <= 10^9\nSo you just work with the intervals in restrictions\nand max height in that interval is the intersection of two lines:\ny1 = (x - left_building_location) + height_left_building\ny2 = (right_building_location - x) + height_right_building\n\n```\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n restrictions += [[1, 0]]\n restrictions.sort() #sort by building number\n\n #if last building is not in restriction add it\n #and its height must be <= n-1 because first building is 0\n if restrictions[-1][0] != n: restrictions.append([n, n-1])\n \n c = 1; c_h = 0\n for i in range(len(restrictions)):\n b,h = restrictions[i]\n\n if (b-c) + c_h < h:\n restrictions[i][1] = (b-c) + c_h\n else:\n c = b; c_h = h \n \n c, c_h = restrictions[-1]\n for i in range(len(restrictions)-1, -1, -1):\n b,h = restrictions[i]\n\n if (c-b) + c_h < h:\n restrictions[i][1] = (c-b) + c_h\n else:\n c = b; c_h = h \n \n ans = 0\n for i in range(len(restrictions) - 1):\n left, left_h = restrictions[i]\n right, right_h = restrictions[i+1]\n\n #y1 = (x - left) + left_h\n #y2 = (rigth - x) + right_h, their intersection is the max_h in that interval\n # x - left + l_h = right - x + r_h\n # x = (right + left + r_h - l_h)/2\n # y = (right + left + r_h - l_h)/2 - left + l_h\n location = (right + left + right_h - left_h)//2 #building_id must be integer\n height = location - left + left_h\n ans = max(ans, height)\n\n return ans\n``` | 0 | You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1 <= i < nums.length - 1`, `(nums[i-1] + nums[i+1]) / 2` is **not** equal to `nums[i]`.
Return _**any** rearrangement of_ `nums` _that meets the requirements_.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** \[1,2,4,5,3\]
**Explanation:**
When i=1, nums\[i\] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.
When i=2, nums\[i\] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.
When i=3, nums\[i\] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.
**Example 2:**
**Input:** nums = \[6,2,0,9,7\]
**Output:** \[9,7,6,2,0\]
**Explanation:**
When i=1, nums\[i\] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.
When i=2, nums\[i\] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.
When i=3, nums\[i\] = 2, and the average of its neighbors is (6+0) / 2 = 3.
**Constraints:**
* `3 <= nums.length <= 105`
* `0 <= nums[i] <= 105` | Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right. |
[Python] Beats 100%, sort + one pass solution, O(nlog(n)) | maximum-building-height | 0 | 1 | I have I think a pretty unique solution, using a single-pass approach to find the max height.\n\nThe main idea of the solution is to "follow the path" of maximum building heights by iterating over the most restrictive restrictions along the indexes.\n\nIf we are at a given restriction `i1, h1`, then we can look at all the following restrictions and find the one that will restrict the most our building heights following this position. The one that will restrict the most the height is the one `i2, h2` such that `i2 + h2` is minimal.\n\n```\n5\n4 4 X\n3 X X 2\n2 1 X\n1 3\n0\n 1 2 3 4 5 6 7 8 9\ni1 = 3, h1 = 2\ni2 = 7, h2 = 3\ni3 = 8, h3 = 1\ni4 = 4, h4 = 4\n```\n\nIn that example, `i3, h3` is more restrictive than `i2, h2`. The good news is, we can easily find the next most restrictive restriction by sorting them by `i + h`.\n\nWe also need to add the first restriction, `1, 0`, as well as handle the case where the restriction does not apply.\n\nIn the previous example, even though `i4 + h4` is lower than `i3 + h3`, we do not consider it because it is "above" the line starting fro `i1 + h1`. In practice, that means skipping restrictions such that `h4 - i4 (0) >= h1 - i1 (-1)`.\n\nGiven `i1, h1` and `i2, h2`, we want to compute the maximum height of the buildings between these. A bit of maths gives us the intersection between the two following lines:\n\n`y = (h1 - i1) + x`\n`y = (h2 + i2) - x`\n\nSolving this equation gives us `y = (h1 + h2 + i2 - i1) / 2`. Because we\'re interested in integer solutions, we can take the integer division by 2.\n\nWithout further ado, the code itself:\n\n```py\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n if not restrictions:\n return n - 1\n restrictions.append([1, 0]) # Add the restriction for the initial position\n restrictions.sort(key=lambda x: x[1] + x[0]) # Sort by increasing i + h\n idx = 0 # The index in the restrictions array\n max_height = 0\n while idx < len(restrictions):\n pos, h = restrictions[idx]\n idx += 1\n while idx < len(restrictions) and restrictions[idx][1] - restrictions[idx][0] >= h - pos:\n\t\t\t\t# skip the next restriction if it is "above" the line starting from the current one\n idx += 1\n if idx == len(restrictions):\n\t\t\t\t# Handles the last restriction: fill the line until the last position at n\n max_height = max(max_height, h + n - pos)\n break\n next_pos, next_h = restrictions[idx]\n\t\t\t# A bit of maths gives us the formula for the maximum height between two consecutive\n\t\t\t# restrictions\n max_height = max(max_height, (h + next_h + next_pos - pos) // 2)\n return max_height\n``` | 0 | You want to build `n` new buildings in a city. The new buildings will be built in a line and are labeled from `1` to `n`.
However, there are city restrictions on the heights of the new buildings:
* The height of each building must be a non-negative integer.
* The height of the first building **must** be `0`.
* The height difference between any two adjacent buildings **cannot exceed** `1`.
Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array `restrictions` where `restrictions[i] = [idi, maxHeighti]` indicates that building `idi` must have a height **less than or equal to** `maxHeighti`.
It is guaranteed that each building will appear **at most once** in `restrictions`, and building `1` will **not** be in `restrictions`.
Return _the **maximum possible height** of the **tallest** building_.
**Example 1:**
**Input:** n = 5, restrictions = \[\[2,1\],\[4,1\]\]
**Output:** 2
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,1,2\], and the tallest building has a height of 2.
**Example 2:**
**Input:** n = 6, restrictions = \[\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,4,5\], and the tallest building has a height of 5.
**Example 3:**
**Input:** n = 10, restrictions = \[\[5,3\],\[2,5\],\[7,4\],\[10,3\]\]
**Output:** 5
**Explanation:** The green area in the image indicates the maximum allowed height for each building.
We can build the buildings with heights \[0,1,2,3,3,4,4,5,4,3\], and the tallest building has a height of 5.
**Constraints:**
* `2 <= n <= 109`
* `0 <= restrictions.length <= min(n - 1, 105)`
* `2 <= idi <= n`
* `idi` is **unique**.
* `0 <= maxHeighti <= 109` | The source array can be imagined as a graph where each index is a node and each allowedSwaps[i] is an edge. Nodes within the same component can be freely swapped with each other. For each component, find the number of common elements. The elements that are not in common will contribute to the total Hamming distance. |
[Python] Beats 100%, sort + one pass solution, O(nlog(n)) | maximum-building-height | 0 | 1 | I have I think a pretty unique solution, using a single-pass approach to find the max height.\n\nThe main idea of the solution is to "follow the path" of maximum building heights by iterating over the most restrictive restrictions along the indexes.\n\nIf we are at a given restriction `i1, h1`, then we can look at all the following restrictions and find the one that will restrict the most our building heights following this position. The one that will restrict the most the height is the one `i2, h2` such that `i2 + h2` is minimal.\n\n```\n5\n4 4 X\n3 X X 2\n2 1 X\n1 3\n0\n 1 2 3 4 5 6 7 8 9\ni1 = 3, h1 = 2\ni2 = 7, h2 = 3\ni3 = 8, h3 = 1\ni4 = 4, h4 = 4\n```\n\nIn that example, `i3, h3` is more restrictive than `i2, h2`. The good news is, we can easily find the next most restrictive restriction by sorting them by `i + h`.\n\nWe also need to add the first restriction, `1, 0`, as well as handle the case where the restriction does not apply.\n\nIn the previous example, even though `i4 + h4` is lower than `i3 + h3`, we do not consider it because it is "above" the line starting fro `i1 + h1`. In practice, that means skipping restrictions such that `h4 - i4 (0) >= h1 - i1 (-1)`.\n\nGiven `i1, h1` and `i2, h2`, we want to compute the maximum height of the buildings between these. A bit of maths gives us the intersection between the two following lines:\n\n`y = (h1 - i1) + x`\n`y = (h2 + i2) - x`\n\nSolving this equation gives us `y = (h1 + h2 + i2 - i1) / 2`. Because we\'re interested in integer solutions, we can take the integer division by 2.\n\nWithout further ado, the code itself:\n\n```py\nclass Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n if not restrictions:\n return n - 1\n restrictions.append([1, 0]) # Add the restriction for the initial position\n restrictions.sort(key=lambda x: x[1] + x[0]) # Sort by increasing i + h\n idx = 0 # The index in the restrictions array\n max_height = 0\n while idx < len(restrictions):\n pos, h = restrictions[idx]\n idx += 1\n while idx < len(restrictions) and restrictions[idx][1] - restrictions[idx][0] >= h - pos:\n\t\t\t\t# skip the next restriction if it is "above" the line starting from the current one\n idx += 1\n if idx == len(restrictions):\n\t\t\t\t# Handles the last restriction: fill the line until the last position at n\n max_height = max(max_height, h + n - pos)\n break\n next_pos, next_h = restrictions[idx]\n\t\t\t# A bit of maths gives us the formula for the maximum height between two consecutive\n\t\t\t# restrictions\n max_height = max(max_height, (h + next_h + next_pos - pos) // 2)\n return max_height\n``` | 0 | You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1 <= i < nums.length - 1`, `(nums[i-1] + nums[i+1]) / 2` is **not** equal to `nums[i]`.
Return _**any** rearrangement of_ `nums` _that meets the requirements_.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** \[1,2,4,5,3\]
**Explanation:**
When i=1, nums\[i\] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.
When i=2, nums\[i\] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.
When i=3, nums\[i\] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.
**Example 2:**
**Input:** nums = \[6,2,0,9,7\]
**Output:** \[9,7,6,2,0\]
**Explanation:**
When i=1, nums\[i\] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.
When i=2, nums\[i\] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.
When i=3, nums\[i\] = 2, and the average of its neighbors is (6+0) / 2 = 3.
**Constraints:**
* `3 <= nums.length <= 105`
* `0 <= nums[i] <= 105` | Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right. |
Python Very Easy Solution | replace-all-digits-with-characters | 0 | 1 | # Code\n```\nclass Solution:\n def replaceDigits(self, s: str) -> str:\n new=""\n for i in range(len(s)):\n if i%2==0:\n new+=s[i]\n else:\n new+=chr(ord(s[i-1])+int(s[i]))\n return new\n``` | 2 | You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices.
There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`.
* For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`.
For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`.
Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`.
**Example 1:**
**Input:** s = "a1c1e1 "
**Output:** "abcdef "
**Explanation:** The digits are replaced as follows:
- s\[1\] -> shift('a',1) = 'b'
- s\[3\] -> shift('c',1) = 'd'
- s\[5\] -> shift('e',1) = 'f'
**Example 2:**
**Input:** s = "a1b2c3d4e "
**Output:** "abbdcfdhe "
**Explanation:** The digits are replaced as follows:
- s\[1\] -> shift('a',1) = 'b'
- s\[3\] -> shift('b',2) = 'd'
- s\[5\] -> shift('c',3) = 'f'
- s\[7\] -> shift('d',4) = 'h'
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists only of lowercase English letters and digits.
* `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`. | Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number |
Python Very Easy Solution | replace-all-digits-with-characters | 0 | 1 | # Code\n```\nclass Solution:\n def replaceDigits(self, s: str) -> str:\n new=""\n for i in range(len(s)):\n if i%2==0:\n new+=s[i]\n else:\n new+=chr(ord(s[i-1])+int(s[i]))\n return new\n``` | 2 | In a garden represented as an infinite 2D grid, there is an apple tree planted at **every** integer coordinate. The apple tree planted at an integer coordinate `(i, j)` has `|i| + |j|` apples growing on it.
You will buy an axis-aligned **square plot** of land that is centered at `(0, 0)`.
Given an integer `neededApples`, return _the **minimum perimeter** of a plot such that **at least**_ `neededApples` _apples are **inside or on** the perimeter of that plot_.
The value of `|x|` is defined as:
* `x` if `x >= 0`
* `-x` if `x < 0`
**Example 1:**
**Input:** neededApples = 1
**Output:** 8
**Explanation:** A square plot of side length 1 does not contain any apples.
However, a square plot of side length 2 has 12 apples inside (as depicted in the image above).
The perimeter is 2 \* 4 = 8.
**Example 2:**
**Input:** neededApples = 13
**Output:** 16
**Example 3:**
**Input:** neededApples = 1000000000
**Output:** 5040
**Constraints:**
* `1 <= neededApples <= 1015` | We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position |
Python Solution | replace-all-digits-with-characters | 0 | 1 | # Code\n```\nclass Solution:\n def replaceDigits(self, s: str) -> str:\n l=list(s)\n for i,j in enumerate(l):\n if j.isdigit():\n l[i]=chr(ord(l[i-1])+int(j))\n return \'\'.join(l)\n```\nDo hit the like button if you find useful! | 3 | You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices.
There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`.
* For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`.
For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`.
Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`.
**Example 1:**
**Input:** s = "a1c1e1 "
**Output:** "abcdef "
**Explanation:** The digits are replaced as follows:
- s\[1\] -> shift('a',1) = 'b'
- s\[3\] -> shift('c',1) = 'd'
- s\[5\] -> shift('e',1) = 'f'
**Example 2:**
**Input:** s = "a1b2c3d4e "
**Output:** "abbdcfdhe "
**Explanation:** The digits are replaced as follows:
- s\[1\] -> shift('a',1) = 'b'
- s\[3\] -> shift('b',2) = 'd'
- s\[5\] -> shift('c',3) = 'f'
- s\[7\] -> shift('d',4) = 'h'
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists only of lowercase English letters and digits.
* `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`. | Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number |
Python Solution | replace-all-digits-with-characters | 0 | 1 | # Code\n```\nclass Solution:\n def replaceDigits(self, s: str) -> str:\n l=list(s)\n for i,j in enumerate(l):\n if j.isdigit():\n l[i]=chr(ord(l[i-1])+int(j))\n return \'\'.join(l)\n```\nDo hit the like button if you find useful! | 3 | In a garden represented as an infinite 2D grid, there is an apple tree planted at **every** integer coordinate. The apple tree planted at an integer coordinate `(i, j)` has `|i| + |j|` apples growing on it.
You will buy an axis-aligned **square plot** of land that is centered at `(0, 0)`.
Given an integer `neededApples`, return _the **minimum perimeter** of a plot such that **at least**_ `neededApples` _apples are **inside or on** the perimeter of that plot_.
The value of `|x|` is defined as:
* `x` if `x >= 0`
* `-x` if `x < 0`
**Example 1:**
**Input:** neededApples = 1
**Output:** 8
**Explanation:** A square plot of side length 1 does not contain any apples.
However, a square plot of side length 2 has 12 apples inside (as depicted in the image above).
The perimeter is 2 \* 4 = 8.
**Example 2:**
**Input:** neededApples = 13
**Output:** 16
**Example 3:**
**Input:** neededApples = 1000000000
**Output:** 5040
**Constraints:**
* `1 <= neededApples <= 1015` | We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position |
Python O(n) solution | replace-all-digits-with-characters | 0 | 1 | \n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Python / Python3\n```\nclass Solution:\n def replaceDigits(self, s: str) -> str:\n ans = \'\'\n for i in range(len(s)):\n if(i & 1):\n asci = ord(s[i - 1]) + int(s[i]) # converting char to ascii value\n ans += chr(asci) # converting ascii to char\n else:\n ans += s[i]\n return ans\n``` | 2 | You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices.
There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`.
* For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`.
For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`.
Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`.
**Example 1:**
**Input:** s = "a1c1e1 "
**Output:** "abcdef "
**Explanation:** The digits are replaced as follows:
- s\[1\] -> shift('a',1) = 'b'
- s\[3\] -> shift('c',1) = 'd'
- s\[5\] -> shift('e',1) = 'f'
**Example 2:**
**Input:** s = "a1b2c3d4e "
**Output:** "abbdcfdhe "
**Explanation:** The digits are replaced as follows:
- s\[1\] -> shift('a',1) = 'b'
- s\[3\] -> shift('b',2) = 'd'
- s\[5\] -> shift('c',3) = 'f'
- s\[7\] -> shift('d',4) = 'h'
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists only of lowercase English letters and digits.
* `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`. | Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number |
Python O(n) solution | replace-all-digits-with-characters | 0 | 1 | \n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Python / Python3\n```\nclass Solution:\n def replaceDigits(self, s: str) -> str:\n ans = \'\'\n for i in range(len(s)):\n if(i & 1):\n asci = ord(s[i - 1]) + int(s[i]) # converting char to ascii value\n ans += chr(asci) # converting ascii to char\n else:\n ans += s[i]\n return ans\n``` | 2 | In a garden represented as an infinite 2D grid, there is an apple tree planted at **every** integer coordinate. The apple tree planted at an integer coordinate `(i, j)` has `|i| + |j|` apples growing on it.
You will buy an axis-aligned **square plot** of land that is centered at `(0, 0)`.
Given an integer `neededApples`, return _the **minimum perimeter** of a plot such that **at least**_ `neededApples` _apples are **inside or on** the perimeter of that plot_.
The value of `|x|` is defined as:
* `x` if `x >= 0`
* `-x` if `x < 0`
**Example 1:**
**Input:** neededApples = 1
**Output:** 8
**Explanation:** A square plot of side length 1 does not contain any apples.
However, a square plot of side length 2 has 12 apples inside (as depicted in the image above).
The perimeter is 2 \* 4 = 8.
**Example 2:**
**Input:** neededApples = 13
**Output:** 16
**Example 3:**
**Input:** neededApples = 1000000000
**Output:** 5040
**Constraints:**
* `1 <= neededApples <= 1015` | We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position |
【Video】Give me 5 minutes - Bests 98.79% - How we think about a solution | seat-reservation-manager | 1 | 1 | # Intuition\nUse min heap\n\n---\n\n# Solution Video\n\nhttps://youtu.be/rgdtMOI5AKA\n\n\u25A0 Timeline of the video\n\n`0:04` Difficulty of Seat Reservation Manager\n`0:52` Two key points to solve Seat Reservation Manager\n`3:25` Coding\n`5:18` Time Complexity and Space Complexity\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: 2,955\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE22)\nThank you for your support!\n\n---\n\n# Approach\n\n## How we think about a solution\n\nIf we only make reservations, this problem is straightforward. But difficilty is \n\n---\n\n\u25A0 Difficulty\n\nWe have unreserve function. Numbers will have gaps.\n\n---\n\nAccording to the description, the numbers we unreserved are available from small numbers again.\n\nWe have two points to solve this question.\n\n---\n\n\u2B50\uFE0F Points\n\n- How we can manage next number.\n\n- How we can manage unreserved numbers.\n\n---\n\n##### How we can manage next number.\n\nThis is very straightforward. Just use `counter` to count from 1 to `n`. Use simple variable.\n\n##### How we can manage unreserved numbers.\n\nIf we have only one unreserved number, it\'s easy to manage it. But what if we have multiple unreserved numbers. How do you manage them?\n\nIn that case, what data structure do you use?\n\nThinking time...\n\n...\uD83D\uDE29\n...\uD83D\uDE05\n...\uD83D\uDE29\n...\uD83D\uDE0F\n...\uD83D\uDE06\n...\uD83D\uDE04\n\nMy answer is to use `min heap`.\n\n---\n\n\u2B50\uFE0F Points\n\nUse min heap because we can manage unreserved numbers from small to large.\n\n---\n\nBasically, we manage the next number with a simple counter, but sometimes we have unreserved numbers which are smaller then current number from counter.\n\nSo, when we make a reverstaion, compare heap[0] with the next number from counter. If heap[0] is small, just pop the small number from heap.\n\nIf not the case, return the next number from counter.\n\n```\nself.next += 1 \nreturn self.next - 1\n```\n\n- Why `-1`?\n\nThat\'s because we add `+1` to `self.next`(counter) to manage next number(e.g. if current number is `3`, we manage `4` for the next reservation). But we need current next number(`3`), that\'s why we need to subtract `-1`.\n\nI hope you understand main idea now.\nLet\'s see a real algorithm.\n\n\n---\n\n\n**Algorithm Overview:**\n\nThe code defines a `SeatManager` class that manages seat reservations for a venue with `n` seats. The class uses a min-heap (implemented as a list) to keep track of unreserved seats. When a reservation is made, the code assigns the smallest available seat to the customer. When a reservation is canceled, the seat is added back to the min-heap for future use.\n\n**Detailed Explanation:**\n1. **Initialization (`__init__` method):**\n - When an instance of the `SeatManager` class is created, it takes an integer `n` as a parameter, which represents the total number of seats in the venue.\n - `self.next` is initialized to 1, representing the next available seat number.\n - `self.heap` is initialized as an empty list and will be used as a min-heap to store unreserved seat numbers.\n\n2. **Reserving a Seat (`reserve` method):**\n - When a customer wants to reserve a seat, the `reserve` method is called.\n - It first checks if the `heap` is not empty and if the smallest seat number in the `heap` (heap[0]) is less than the `next`. If so, it means there are unreserved seats available, and it\'s time to assign one.\n - If the condition is met, the smallest seat number is removed from the `heap` using `heapq.heappop()`, and that seat number is returned to the customer, indicating a successful reservation.\n - If the condition is not met, the `next` seat number is assigned to the customer, indicating the reservation of the next available seat.\n - In either case, `self.next` is incremented to prepare for the next reservation.\n\n3. **Unreserving a Seat (`unreserve` method):**\n - When a customer decides to unreserve a seat, the `unreserve` method is called with the `seatNumber` as an argument.\n - The `seatNumber` is added back to the `heap` using `heapq.heappush()`. This operation ensures that the unreserved seat is stored in the `heap` and will be allocated to future customers in ascending order.\n\nIn summary, the `SeatManager` class efficiently manages seat reservations and unreservations using a min-heap, ensuring that the smallest available seat is always assigned to customers. This algorithm provides an elegant way to optimize seat allocation in a venue.\n\n\n# Complexity\n- Time complexity:\n`__init__` is $$O(1)$$\n`reserve` is $$O(log n)$$\n`unreserve` is $$O(log n)$$\n\n- Space complexity: $$O(n)$$\n\n\n```python []\nclass SeatManager:\n\n def __init__(self, n: int):\n self.next = 1\n self.heap = []\n\n def reserve(self) -> int:\n if self.heap and self.heap[0] < self.next:\n return heapq.heappop(self.heap)\n\n self.next += 1 \n return self.next - 1\n\n def unreserve(self, seatNumber: int) -> None:\n heapq.heappush(self.heap, seatNumber)\n\n```\n```javascript []\nclass SeatManager {\n constructor(n) {\n this.next = 1;\n this.heap = [];\n }\n\n reserve() {\n if (this.heap.length > 0 && this.heap[0] < this.next) {\n return this.heap.shift();\n }\n\n this.next += 1;\n return this.next - 1;\n }\n\n unreserve(seatNumber) {\n this.enqueueWithPriority(this.heap, seatNumber);\n }\n\n enqueueWithPriority(queue, value) {\n let i = 0;\n while (i < queue.length && queue[i] < value) {\n i++;\n }\n queue.splice(i, 0, value);\n }\n}\n```\n```java []\nclass SeatManager {\n\n private int next;\n private PriorityQueue<Integer> heap;\n\n public SeatManager(int n) {\n next = 1;\n heap = new PriorityQueue<>();\n }\n\n public int reserve() {\n if (!heap.isEmpty() && heap.peek() < next) {\n return heap.poll();\n }\n\n next++;\n return next - 1;\n }\n\n public void unreserve(int seatNumber) {\n heap.offer(seatNumber);\n }\n}\n\n/**\n * Your SeatManager object will be instantiated and called as such:\n * SeatManager obj = new SeatManager(n);\n * int param_1 = obj.reserve();\n * obj.unreserve(seatNumber);\n */\n```\n```C++ []\nclass SeatManager {\n\nprivate:\n int next;\n priority_queue<int, vector<int>, greater<int>> heap;\n\npublic:\n SeatManager(int n) {\n next = 1;\n }\n\n int reserve() {\n if (!heap.empty() && heap.top() < next) {\n int reservedSeat = heap.top();\n heap.pop();\n return reservedSeat;\n }\n\n next++;\n return next - 1;\n }\n\n void unreserve(int seatNumber) {\n heap.push(seatNumber);\n }\n};\n\n/**\n * Your SeatManager object will be instantiated and called as such:\n * SeatManager* obj = new SeatManager(n);\n * int param_1 = obj->reserve();\n * obj->unreserve(seatNumber);\n */\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### My next daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/eliminate-maximum-number-of-monsters/solutions/4259212/video-give-me-10-minutes-on-solution-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/2tUBAJEn-S8\n\n\u25A0 Timeline of the video\n\n`0:04` Heap solution I came up with at first\n`2:38` Two key points with O(n) solution for Eliminate Maximum Number of Monsters\n`2:59` Explain the first key point\n`5:08` Explain the second key point\n`6:19` How we can eliminate monsters that are out of bounds\n`8:48` Let\'s see another case\n`9:52` How we can calculate eliminated numbers\n`10:56` Coding\n`13:03` Time Complexity and Space Complexity\n\n### My previous daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/build-an-array-with-stack-operations/solutions/4244407/video-give-me-5-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/MCYiEw2zvNw\n\n\u25A0 Timeline of the video\n\n`0:04` Basic idea to solve this question\n`1:04` How do you operate each number from the steam of integers?\n`3:34` What operation we need for the two patterns\n`5:17` Coding\n`6:37` Time Complexity and Space Complexity | 23 | Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`.
Implement the `SeatManager` class:
* `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available.
* `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number.
* `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`.
**Example 1:**
**Input**
\[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\]
\[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\]
**Output**
\[null, 1, 2, null, 2, 3, 4, 5, null\]
**Explanation**
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\].
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3.
seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4.
seatManager.reserve(); // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\].
**Constraints:**
* `1 <= n <= 105`
* `1 <= seatNumber <= n`
* For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat.
* For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved.
* At most `105` calls **in total** will be made to `reserve` and `unreserve`. | For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix. |
【Video】Give me 5 minutes - Bests 98.79% - How we think about a solution | seat-reservation-manager | 1 | 1 | # Intuition\nUse min heap\n\n---\n\n# Solution Video\n\nhttps://youtu.be/rgdtMOI5AKA\n\n\u25A0 Timeline of the video\n\n`0:04` Difficulty of Seat Reservation Manager\n`0:52` Two key points to solve Seat Reservation Manager\n`3:25` Coding\n`5:18` Time Complexity and Space Complexity\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: 2,955\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE22)\nThank you for your support!\n\n---\n\n# Approach\n\n## How we think about a solution\n\nIf we only make reservations, this problem is straightforward. But difficilty is \n\n---\n\n\u25A0 Difficulty\n\nWe have unreserve function. Numbers will have gaps.\n\n---\n\nAccording to the description, the numbers we unreserved are available from small numbers again.\n\nWe have two points to solve this question.\n\n---\n\n\u2B50\uFE0F Points\n\n- How we can manage next number.\n\n- How we can manage unreserved numbers.\n\n---\n\n##### How we can manage next number.\n\nThis is very straightforward. Just use `counter` to count from 1 to `n`. Use simple variable.\n\n##### How we can manage unreserved numbers.\n\nIf we have only one unreserved number, it\'s easy to manage it. But what if we have multiple unreserved numbers. How do you manage them?\n\nIn that case, what data structure do you use?\n\nThinking time...\n\n...\uD83D\uDE29\n...\uD83D\uDE05\n...\uD83D\uDE29\n...\uD83D\uDE0F\n...\uD83D\uDE06\n...\uD83D\uDE04\n\nMy answer is to use `min heap`.\n\n---\n\n\u2B50\uFE0F Points\n\nUse min heap because we can manage unreserved numbers from small to large.\n\n---\n\nBasically, we manage the next number with a simple counter, but sometimes we have unreserved numbers which are smaller then current number from counter.\n\nSo, when we make a reverstaion, compare heap[0] with the next number from counter. If heap[0] is small, just pop the small number from heap.\n\nIf not the case, return the next number from counter.\n\n```\nself.next += 1 \nreturn self.next - 1\n```\n\n- Why `-1`?\n\nThat\'s because we add `+1` to `self.next`(counter) to manage next number(e.g. if current number is `3`, we manage `4` for the next reservation). But we need current next number(`3`), that\'s why we need to subtract `-1`.\n\nI hope you understand main idea now.\nLet\'s see a real algorithm.\n\n\n---\n\n\n**Algorithm Overview:**\n\nThe code defines a `SeatManager` class that manages seat reservations for a venue with `n` seats. The class uses a min-heap (implemented as a list) to keep track of unreserved seats. When a reservation is made, the code assigns the smallest available seat to the customer. When a reservation is canceled, the seat is added back to the min-heap for future use.\n\n**Detailed Explanation:**\n1. **Initialization (`__init__` method):**\n - When an instance of the `SeatManager` class is created, it takes an integer `n` as a parameter, which represents the total number of seats in the venue.\n - `self.next` is initialized to 1, representing the next available seat number.\n - `self.heap` is initialized as an empty list and will be used as a min-heap to store unreserved seat numbers.\n\n2. **Reserving a Seat (`reserve` method):**\n - When a customer wants to reserve a seat, the `reserve` method is called.\n - It first checks if the `heap` is not empty and if the smallest seat number in the `heap` (heap[0]) is less than the `next`. If so, it means there are unreserved seats available, and it\'s time to assign one.\n - If the condition is met, the smallest seat number is removed from the `heap` using `heapq.heappop()`, and that seat number is returned to the customer, indicating a successful reservation.\n - If the condition is not met, the `next` seat number is assigned to the customer, indicating the reservation of the next available seat.\n - In either case, `self.next` is incremented to prepare for the next reservation.\n\n3. **Unreserving a Seat (`unreserve` method):**\n - When a customer decides to unreserve a seat, the `unreserve` method is called with the `seatNumber` as an argument.\n - The `seatNumber` is added back to the `heap` using `heapq.heappush()`. This operation ensures that the unreserved seat is stored in the `heap` and will be allocated to future customers in ascending order.\n\nIn summary, the `SeatManager` class efficiently manages seat reservations and unreservations using a min-heap, ensuring that the smallest available seat is always assigned to customers. This algorithm provides an elegant way to optimize seat allocation in a venue.\n\n\n# Complexity\n- Time complexity:\n`__init__` is $$O(1)$$\n`reserve` is $$O(log n)$$\n`unreserve` is $$O(log n)$$\n\n- Space complexity: $$O(n)$$\n\n\n```python []\nclass SeatManager:\n\n def __init__(self, n: int):\n self.next = 1\n self.heap = []\n\n def reserve(self) -> int:\n if self.heap and self.heap[0] < self.next:\n return heapq.heappop(self.heap)\n\n self.next += 1 \n return self.next - 1\n\n def unreserve(self, seatNumber: int) -> None:\n heapq.heappush(self.heap, seatNumber)\n\n```\n```javascript []\nclass SeatManager {\n constructor(n) {\n this.next = 1;\n this.heap = [];\n }\n\n reserve() {\n if (this.heap.length > 0 && this.heap[0] < this.next) {\n return this.heap.shift();\n }\n\n this.next += 1;\n return this.next - 1;\n }\n\n unreserve(seatNumber) {\n this.enqueueWithPriority(this.heap, seatNumber);\n }\n\n enqueueWithPriority(queue, value) {\n let i = 0;\n while (i < queue.length && queue[i] < value) {\n i++;\n }\n queue.splice(i, 0, value);\n }\n}\n```\n```java []\nclass SeatManager {\n\n private int next;\n private PriorityQueue<Integer> heap;\n\n public SeatManager(int n) {\n next = 1;\n heap = new PriorityQueue<>();\n }\n\n public int reserve() {\n if (!heap.isEmpty() && heap.peek() < next) {\n return heap.poll();\n }\n\n next++;\n return next - 1;\n }\n\n public void unreserve(int seatNumber) {\n heap.offer(seatNumber);\n }\n}\n\n/**\n * Your SeatManager object will be instantiated and called as such:\n * SeatManager obj = new SeatManager(n);\n * int param_1 = obj.reserve();\n * obj.unreserve(seatNumber);\n */\n```\n```C++ []\nclass SeatManager {\n\nprivate:\n int next;\n priority_queue<int, vector<int>, greater<int>> heap;\n\npublic:\n SeatManager(int n) {\n next = 1;\n }\n\n int reserve() {\n if (!heap.empty() && heap.top() < next) {\n int reservedSeat = heap.top();\n heap.pop();\n return reservedSeat;\n }\n\n next++;\n return next - 1;\n }\n\n void unreserve(int seatNumber) {\n heap.push(seatNumber);\n }\n};\n\n/**\n * Your SeatManager object will be instantiated and called as such:\n * SeatManager* obj = new SeatManager(n);\n * int param_1 = obj->reserve();\n * obj->unreserve(seatNumber);\n */\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### My next daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/eliminate-maximum-number-of-monsters/solutions/4259212/video-give-me-10-minutes-on-solution-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/2tUBAJEn-S8\n\n\u25A0 Timeline of the video\n\n`0:04` Heap solution I came up with at first\n`2:38` Two key points with O(n) solution for Eliminate Maximum Number of Monsters\n`2:59` Explain the first key point\n`5:08` Explain the second key point\n`6:19` How we can eliminate monsters that are out of bounds\n`8:48` Let\'s see another case\n`9:52` How we can calculate eliminated numbers\n`10:56` Coding\n`13:03` Time Complexity and Space Complexity\n\n### My previous daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/build-an-array-with-stack-operations/solutions/4244407/video-give-me-5-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/MCYiEw2zvNw\n\n\u25A0 Timeline of the video\n\n`0:04` Basic idea to solve this question\n`1:04` How do you operate each number from the steam of integers?\n`3:34` What operation we need for the two patterns\n`5:17` Coding\n`6:37` Time Complexity and Space Complexity | 23 | A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s.
* For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special.
* In contrast, `[2,1,0]`, `[1]`, and `[0,1,2,0]` are not special.
Given an array `nums` (consisting of **only** integers `0`, `1`, and `2`), return _the **number of different subsequences** that are special_. Since the answer may be very large, **return it modulo** `109 + 7`.
A **subsequence** of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are **different** if the **set of indices** chosen are different.
**Example 1:**
**Input:** nums = \[0,1,2,2\]
**Output:** 3
**Explanation:** The special subsequences are bolded \[**0**,**1**,**2**,2\], \[**0**,**1**,2,**2**\], and \[**0**,**1**,**2**,**2**\].
**Example 2:**
**Input:** nums = \[2,2,0,0\]
**Output:** 0
**Explanation:** There are no special subsequences in \[2,2,0,0\].
**Example 3:**
**Input:** nums = \[0,1,2,0,1,2\]
**Output:** 7
**Explanation:** The special subsequences are bolded:
- \[**0**,**1**,**2**,0,1,2\]
- \[**0**,**1**,2,0,1,**2**\]
- \[**0**,**1**,**2**,0,1,**2**\]
- \[**0**,**1**,2,0,**1**,**2**\]
- \[**0**,1,2,**0**,**1**,**2**\]
- \[**0**,1,2,0,**1**,**2**\]
- \[0,1,2,**0**,**1**,**2**\]
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 2` | You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an element, in a reasonable time. Ordered sets support these operations. |
✅ 98.78% Counter and Min-Heap | seat-reservation-manager | 1 | 1 | # Intuition\nWhen we think about reserving and unreserving seats, our first thought is that we need to keep track of the available seats in an ordered fashion. We should be able to reserve the smallest available seat quickly and also be able to unreserve any seat efficiently. This leads us to think of data structures like sorted lists or heaps.\n\n# Live Coding & More\nhttps://youtu.be/GUuaJSMM2_8?si=U3bh4PfssOM8266_\n\n# Approach\nThe approach we\'ve taken is a combination of a **Counter and Min-Heap** strategy.\n\n1. **Counter (`last`)**: This keeps track of the latest continuous seat that\'s been reserved. For example, if seats 1, 2, and 3 are reserved and no unreservations have been made, `last` will be 3.\n \n2. **Min-Heap (`pq`)**: This is used to keep track of seats that have been unreserved and are out of the continuous sequence. For instance, if someone reserves seats 1, 2, and 3, and then unreserves seat 2, then seat 2 will be added to the min-heap.\n\nThe logic for the `reserve` and `unreserve` functions is as follows:\n\n- `reserve`:\n - If the min-heap is empty, simply increment the `last` counter and return it.\n - If the min-heap has seats (i.e., there are unreserved seats), pop the smallest seat from the heap and return it.\n\n- `unreserve`:\n - If the seat being unreserved is the last seat in the continuous sequence, decrement the `last` counter.\n - Otherwise, add the unreserved seat to the min-heap.\n\n# Complexity\n- **Time complexity**:\n - `reserve`: Average $O(1)$ (when using the counter), but $O(\\log n)$ (when using the min-heap).\n - `unreserve`: $O(\\log n)$ (due to the min-heap operation).\n\n- **Space complexity**: $O(n)$. This is the worst-case scenario where all seats have been reserved and then unreserved, filling up the min-heap.\n\n# Code\n``` Python []\nclass SeatManager:\n\n def __init__(self, n: int):\n self.last = 0\n self.pq = []\n\n def reserve(self) -> int:\n if not self.pq:\n self.last += 1\n return self.last\n return heapq.heappop(self.pq)\n\n def unreserve(self, seatNumber: int) -> None:\n if seatNumber == self.last:\n self.last -= 1\n else:\n heapq.heappush(self.pq, seatNumber)\n```\n``` Java []\npublic class SeatManager {\n private int last;\n private PriorityQueue<Integer> pq;\n\n public SeatManager(int n) {\n this.last = 0;\n this.pq = new PriorityQueue<>();\n }\n\n public int reserve() {\n if (pq.isEmpty()) {\n return ++last;\n } else {\n return pq.poll();\n }\n }\n\n public void unreserve(int seatNumber) {\n if (seatNumber == last) {\n --last;\n } else {\n pq.offer(seatNumber);\n }\n }\n}\n```\n``` C++ []\nclass SeatManager {\nprivate:\n int last;\n std::priority_queue<int, std::vector<int>, std::greater<int>> pq;\n\npublic:\n SeatManager(int n) : last(0) {}\n\n int reserve() {\n if (pq.empty()) {\n return ++last;\n } else {\n int seat = pq.top();\n pq.pop();\n return seat;\n }\n }\n\n void unreserve(int seatNumber) {\n if (seatNumber == last) {\n --last;\n } else {\n pq.push(seatNumber);\n }\n }\n};\n```\n``` C# []\npublic class SeatManager {\n private int last;\n private SortedSet<int> pq;\n\n public SeatManager(int n) {\n this.last = 0;\n this.pq = new SortedSet<int>();\n }\n\n public int Reserve() {\n if (!pq.Any()) {\n return ++last;\n } else {\n int seat = pq.Min;\n pq.Remove(seat);\n return seat;\n }\n }\n\n public void Unreserve(int seatNumber) {\n if (seatNumber == last) {\n --last;\n } else {\n pq.Add(seatNumber);\n }\n }\n}\n```\n``` Go []\npackage main\n\nimport (\n\t"container/heap"\n)\n\ntype SeatManager struct {\n\tlast int\n\tpq IntHeap\n}\n\nfunc Constructor(n int) SeatManager {\n\treturn SeatManager{\n\t\tlast: 0,\n\t\tpq: make(IntHeap, 0),\n\t}\n}\n\nfunc (this *SeatManager) Reserve() int {\n\tif len(this.pq) == 0 {\n\t\tthis.last++\n\t\treturn this.last\n\t}\n\treturn heap.Pop(&this.pq).(int)\n}\n\nfunc (this *SeatManager) Unreserve(seatNumber int) {\n\tif seatNumber == this.last {\n\t\tthis.last--\n\t} else {\n\t\theap.Push(&this.pq, seatNumber)\n\t}\n}\n\ntype IntHeap []int\n\nfunc (h IntHeap) Len() int { return len(h) }\nfunc (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }\nfunc (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }\n\nfunc (h *IntHeap) Push(x interface{}) {\n\t*h = append(*h, x.(int))\n}\n\nfunc (h *IntHeap) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}\n```\n``` Rust []\nuse std::collections::BinaryHeap;\nuse std::cmp::Reverse;\n\nstruct SeatManager {\n last: i32,\n pq: BinaryHeap<Reverse<i32>>,\n}\n\nimpl SeatManager {\n fn new(n: i32) -> Self {\n SeatManager {\n last: 0,\n pq: BinaryHeap::new(),\n }\n }\n\n fn reserve(&mut self) -> i32 {\n if self.pq.is_empty() {\n self.last += 1;\n self.last\n } else {\n let seat = self.pq.pop().unwrap().0;\n seat\n }\n }\n\n fn unreserve(&mut self, seat_number: i32) {\n if seat_number == self.last {\n self.last -= 1;\n } else {\n self.pq.push(Reverse(seat_number));\n }\n }\n}\n```\n``` JavaScript []\nclass SeatManager {\n constructor(n) {\n this.last = 0;\n this.pq = [];\n }\n\n reserve() {\n if (this.pq.length === 0) {\n return ++this.last;\n } else {\n this.pq.sort((a, b) => a - b);\n return this.pq.shift();\n }\n }\n\n unreserve(seatNumber) {\n if (seatNumber === this.last) {\n this.last--;\n } else {\n this.pq.push(seatNumber);\n }\n }\n}\n```\n``` PHP []\n<?php\nclass SeatManager {\n private $last;\n private $pq;\n\n function __construct($n) {\n $this->last = 0;\n $this->pq = new SplPriorityQueue();\n }\n\n function reserve() {\n if ($this->pq->isEmpty()) {\n return ++$this->last;\n } else {\n return $this->pq->extract();\n }\n }\n\n function unreserve($seatNumber) {\n if ($seatNumber == $this->last) {\n $this->last--;\n } else {\n $this->pq->insert($seatNumber, -$seatNumber);\n }\n }\n}\n?>\n```\n\n# Performance\n\n| Language | Execution Time (ms) | Memory Usage (MB) |\n|----------|---------------------|-------------------|\n| Java | 29 | 91.1 |\n| Rust | 55 | 28.2 |\n| C++ | 260 | 142.2 |\n| Go | 288 | 30.2 |\n| PHP | 324 | 63.6 |\n| Python3 | 361 | 42.5 |\n| C# | 434 | 108.7 |\n| JavaScript | 589 | 120.4 |\n\n\n\n\n# Why does it work?\nThe approach works because we are always prioritizing the smallest available seat. The counter (`last`) ensures that if we are in a continuous sequence of reservations, we avoid any complex operations and simply increment a value. The min-heap ensures that once seats are unreserved and out of sequence, we can still reserve the smallest available seat efficiently.\n\n# What optimization was made?\nThe major optimization here is the introduction of the `last` counter. Instead of always relying on a heap or list operation (which can be log-linear or linear in time), we often use a constant-time operation when the seats are reserved in sequence.\n\n# What did we learn?\nUsing a combination of simple counters and more complex data structures like heaps can offer a balance between simplicity and efficiency. The counter handles the common case (continuous seat reservation), and the heap handles the edge case (out-of-sequence unreservations). This ensures that our solution is both fast and handles all possible scenarios. | 90 | Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`.
Implement the `SeatManager` class:
* `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available.
* `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number.
* `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`.
**Example 1:**
**Input**
\[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\]
\[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\]
**Output**
\[null, 1, 2, null, 2, 3, 4, 5, null\]
**Explanation**
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\].
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3.
seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4.
seatManager.reserve(); // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\].
**Constraints:**
* `1 <= n <= 105`
* `1 <= seatNumber <= n`
* For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat.
* For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved.
* At most `105` calls **in total** will be made to `reserve` and `unreserve`. | For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix. |
✅ 98.78% Counter and Min-Heap | seat-reservation-manager | 1 | 1 | # Intuition\nWhen we think about reserving and unreserving seats, our first thought is that we need to keep track of the available seats in an ordered fashion. We should be able to reserve the smallest available seat quickly and also be able to unreserve any seat efficiently. This leads us to think of data structures like sorted lists or heaps.\n\n# Live Coding & More\nhttps://youtu.be/GUuaJSMM2_8?si=U3bh4PfssOM8266_\n\n# Approach\nThe approach we\'ve taken is a combination of a **Counter and Min-Heap** strategy.\n\n1. **Counter (`last`)**: This keeps track of the latest continuous seat that\'s been reserved. For example, if seats 1, 2, and 3 are reserved and no unreservations have been made, `last` will be 3.\n \n2. **Min-Heap (`pq`)**: This is used to keep track of seats that have been unreserved and are out of the continuous sequence. For instance, if someone reserves seats 1, 2, and 3, and then unreserves seat 2, then seat 2 will be added to the min-heap.\n\nThe logic for the `reserve` and `unreserve` functions is as follows:\n\n- `reserve`:\n - If the min-heap is empty, simply increment the `last` counter and return it.\n - If the min-heap has seats (i.e., there are unreserved seats), pop the smallest seat from the heap and return it.\n\n- `unreserve`:\n - If the seat being unreserved is the last seat in the continuous sequence, decrement the `last` counter.\n - Otherwise, add the unreserved seat to the min-heap.\n\n# Complexity\n- **Time complexity**:\n - `reserve`: Average $O(1)$ (when using the counter), but $O(\\log n)$ (when using the min-heap).\n - `unreserve`: $O(\\log n)$ (due to the min-heap operation).\n\n- **Space complexity**: $O(n)$. This is the worst-case scenario where all seats have been reserved and then unreserved, filling up the min-heap.\n\n# Code\n``` Python []\nclass SeatManager:\n\n def __init__(self, n: int):\n self.last = 0\n self.pq = []\n\n def reserve(self) -> int:\n if not self.pq:\n self.last += 1\n return self.last\n return heapq.heappop(self.pq)\n\n def unreserve(self, seatNumber: int) -> None:\n if seatNumber == self.last:\n self.last -= 1\n else:\n heapq.heappush(self.pq, seatNumber)\n```\n``` Java []\npublic class SeatManager {\n private int last;\n private PriorityQueue<Integer> pq;\n\n public SeatManager(int n) {\n this.last = 0;\n this.pq = new PriorityQueue<>();\n }\n\n public int reserve() {\n if (pq.isEmpty()) {\n return ++last;\n } else {\n return pq.poll();\n }\n }\n\n public void unreserve(int seatNumber) {\n if (seatNumber == last) {\n --last;\n } else {\n pq.offer(seatNumber);\n }\n }\n}\n```\n``` C++ []\nclass SeatManager {\nprivate:\n int last;\n std::priority_queue<int, std::vector<int>, std::greater<int>> pq;\n\npublic:\n SeatManager(int n) : last(0) {}\n\n int reserve() {\n if (pq.empty()) {\n return ++last;\n } else {\n int seat = pq.top();\n pq.pop();\n return seat;\n }\n }\n\n void unreserve(int seatNumber) {\n if (seatNumber == last) {\n --last;\n } else {\n pq.push(seatNumber);\n }\n }\n};\n```\n``` C# []\npublic class SeatManager {\n private int last;\n private SortedSet<int> pq;\n\n public SeatManager(int n) {\n this.last = 0;\n this.pq = new SortedSet<int>();\n }\n\n public int Reserve() {\n if (!pq.Any()) {\n return ++last;\n } else {\n int seat = pq.Min;\n pq.Remove(seat);\n return seat;\n }\n }\n\n public void Unreserve(int seatNumber) {\n if (seatNumber == last) {\n --last;\n } else {\n pq.Add(seatNumber);\n }\n }\n}\n```\n``` Go []\npackage main\n\nimport (\n\t"container/heap"\n)\n\ntype SeatManager struct {\n\tlast int\n\tpq IntHeap\n}\n\nfunc Constructor(n int) SeatManager {\n\treturn SeatManager{\n\t\tlast: 0,\n\t\tpq: make(IntHeap, 0),\n\t}\n}\n\nfunc (this *SeatManager) Reserve() int {\n\tif len(this.pq) == 0 {\n\t\tthis.last++\n\t\treturn this.last\n\t}\n\treturn heap.Pop(&this.pq).(int)\n}\n\nfunc (this *SeatManager) Unreserve(seatNumber int) {\n\tif seatNumber == this.last {\n\t\tthis.last--\n\t} else {\n\t\theap.Push(&this.pq, seatNumber)\n\t}\n}\n\ntype IntHeap []int\n\nfunc (h IntHeap) Len() int { return len(h) }\nfunc (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }\nfunc (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }\n\nfunc (h *IntHeap) Push(x interface{}) {\n\t*h = append(*h, x.(int))\n}\n\nfunc (h *IntHeap) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}\n```\n``` Rust []\nuse std::collections::BinaryHeap;\nuse std::cmp::Reverse;\n\nstruct SeatManager {\n last: i32,\n pq: BinaryHeap<Reverse<i32>>,\n}\n\nimpl SeatManager {\n fn new(n: i32) -> Self {\n SeatManager {\n last: 0,\n pq: BinaryHeap::new(),\n }\n }\n\n fn reserve(&mut self) -> i32 {\n if self.pq.is_empty() {\n self.last += 1;\n self.last\n } else {\n let seat = self.pq.pop().unwrap().0;\n seat\n }\n }\n\n fn unreserve(&mut self, seat_number: i32) {\n if seat_number == self.last {\n self.last -= 1;\n } else {\n self.pq.push(Reverse(seat_number));\n }\n }\n}\n```\n``` JavaScript []\nclass SeatManager {\n constructor(n) {\n this.last = 0;\n this.pq = [];\n }\n\n reserve() {\n if (this.pq.length === 0) {\n return ++this.last;\n } else {\n this.pq.sort((a, b) => a - b);\n return this.pq.shift();\n }\n }\n\n unreserve(seatNumber) {\n if (seatNumber === this.last) {\n this.last--;\n } else {\n this.pq.push(seatNumber);\n }\n }\n}\n```\n``` PHP []\n<?php\nclass SeatManager {\n private $last;\n private $pq;\n\n function __construct($n) {\n $this->last = 0;\n $this->pq = new SplPriorityQueue();\n }\n\n function reserve() {\n if ($this->pq->isEmpty()) {\n return ++$this->last;\n } else {\n return $this->pq->extract();\n }\n }\n\n function unreserve($seatNumber) {\n if ($seatNumber == $this->last) {\n $this->last--;\n } else {\n $this->pq->insert($seatNumber, -$seatNumber);\n }\n }\n}\n?>\n```\n\n# Performance\n\n| Language | Execution Time (ms) | Memory Usage (MB) |\n|----------|---------------------|-------------------|\n| Java | 29 | 91.1 |\n| Rust | 55 | 28.2 |\n| C++ | 260 | 142.2 |\n| Go | 288 | 30.2 |\n| PHP | 324 | 63.6 |\n| Python3 | 361 | 42.5 |\n| C# | 434 | 108.7 |\n| JavaScript | 589 | 120.4 |\n\n\n\n\n# Why does it work?\nThe approach works because we are always prioritizing the smallest available seat. The counter (`last`) ensures that if we are in a continuous sequence of reservations, we avoid any complex operations and simply increment a value. The min-heap ensures that once seats are unreserved and out of sequence, we can still reserve the smallest available seat efficiently.\n\n# What optimization was made?\nThe major optimization here is the introduction of the `last` counter. Instead of always relying on a heap or list operation (which can be log-linear or linear in time), we often use a constant-time operation when the seats are reserved in sequence.\n\n# What did we learn?\nUsing a combination of simple counters and more complex data structures like heaps can offer a balance between simplicity and efficiency. The counter handles the common case (continuous seat reservation), and the heap handles the edge case (out-of-sequence unreservations). This ensures that our solution is both fast and handles all possible scenarios. | 90 | A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s.
* For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special.
* In contrast, `[2,1,0]`, `[1]`, and `[0,1,2,0]` are not special.
Given an array `nums` (consisting of **only** integers `0`, `1`, and `2`), return _the **number of different subsequences** that are special_. Since the answer may be very large, **return it modulo** `109 + 7`.
A **subsequence** of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are **different** if the **set of indices** chosen are different.
**Example 1:**
**Input:** nums = \[0,1,2,2\]
**Output:** 3
**Explanation:** The special subsequences are bolded \[**0**,**1**,**2**,2\], \[**0**,**1**,2,**2**\], and \[**0**,**1**,**2**,**2**\].
**Example 2:**
**Input:** nums = \[2,2,0,0\]
**Output:** 0
**Explanation:** There are no special subsequences in \[2,2,0,0\].
**Example 3:**
**Input:** nums = \[0,1,2,0,1,2\]
**Output:** 7
**Explanation:** The special subsequences are bolded:
- \[**0**,**1**,**2**,0,1,2\]
- \[**0**,**1**,2,0,1,**2**\]
- \[**0**,**1**,**2**,0,1,**2**\]
- \[**0**,**1**,2,0,**1**,**2**\]
- \[**0**,1,2,**0**,**1**,**2**\]
- \[**0**,1,2,0,**1**,**2**\]
- \[0,1,2,**0**,**1**,**2**\]
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 2` | You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an element, in a reasonable time. Ordered sets support these operations. |
Beats 94.24% (runtime) and 100% (memory) of users with Python3 (using Counter and MinHeap) | seat-reservation-manager | 0 | 1 | # Using Counter and MinHeap\n- Instead of pre-initialization `1` to `n` array, use counter\n- Whenever we unreserve the seat, push that element in heap. Note that all the elements in heap will smaller than the counter.\n- So while reserving the seat, extract min element from heap and if heap is empty, get the value from counter.\n\n\n\n\n# Code\n```\nclass SeatManager:\n def __init__(self, n: int):\n self.hq = []\n self.current = 0\n\n def reserve(self) -> int:\n if self.hq:\n return heapq.heappop(self.hq)\n self.current += 1\n return self.current\n\n def unreserve(self, seatNumber: int) -> None:\n heapq.heappush(self.hq, seatNumber)\n```\n | 2 | Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`.
Implement the `SeatManager` class:
* `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available.
* `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number.
* `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`.
**Example 1:**
**Input**
\[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\]
\[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\]
**Output**
\[null, 1, 2, null, 2, 3, 4, 5, null\]
**Explanation**
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\].
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3.
seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4.
seatManager.reserve(); // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\].
**Constraints:**
* `1 <= n <= 105`
* `1 <= seatNumber <= n`
* For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat.
* For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved.
* At most `105` calls **in total** will be made to `reserve` and `unreserve`. | For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix. |
Beats 94.24% (runtime) and 100% (memory) of users with Python3 (using Counter and MinHeap) | seat-reservation-manager | 0 | 1 | # Using Counter and MinHeap\n- Instead of pre-initialization `1` to `n` array, use counter\n- Whenever we unreserve the seat, push that element in heap. Note that all the elements in heap will smaller than the counter.\n- So while reserving the seat, extract min element from heap and if heap is empty, get the value from counter.\n\n\n\n\n# Code\n```\nclass SeatManager:\n def __init__(self, n: int):\n self.hq = []\n self.current = 0\n\n def reserve(self) -> int:\n if self.hq:\n return heapq.heappop(self.hq)\n self.current += 1\n return self.current\n\n def unreserve(self, seatNumber: int) -> None:\n heapq.heappush(self.hq, seatNumber)\n```\n | 2 | A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s.
* For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special.
* In contrast, `[2,1,0]`, `[1]`, and `[0,1,2,0]` are not special.
Given an array `nums` (consisting of **only** integers `0`, `1`, and `2`), return _the **number of different subsequences** that are special_. Since the answer may be very large, **return it modulo** `109 + 7`.
A **subsequence** of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are **different** if the **set of indices** chosen are different.
**Example 1:**
**Input:** nums = \[0,1,2,2\]
**Output:** 3
**Explanation:** The special subsequences are bolded \[**0**,**1**,**2**,2\], \[**0**,**1**,2,**2**\], and \[**0**,**1**,**2**,**2**\].
**Example 2:**
**Input:** nums = \[2,2,0,0\]
**Output:** 0
**Explanation:** There are no special subsequences in \[2,2,0,0\].
**Example 3:**
**Input:** nums = \[0,1,2,0,1,2\]
**Output:** 7
**Explanation:** The special subsequences are bolded:
- \[**0**,**1**,**2**,0,1,2\]
- \[**0**,**1**,2,0,1,**2**\]
- \[**0**,**1**,**2**,0,1,**2**\]
- \[**0**,**1**,2,0,**1**,**2**\]
- \[**0**,1,2,**0**,**1**,**2**\]
- \[**0**,1,2,0,**1**,**2**\]
- \[0,1,2,**0**,**1**,**2**\]
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 2` | You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an element, in a reasonable time. Ordered sets support these operations. |
Python | Optimized Min Heap | O(log n) | 99% T 98% S | seat-reservation-manager | 0 | 1 | **Optimized Priority Queue Solution**\n\nOur objective is to reserve and unreserve seats with a set of commands. Ideally we would iterate from 1 to n in order to reserve the inital set of n unreserved seats, and our biggest challenge is reserving seats after a series of seats have been unreserved. We need a way to store and track the minimum of this set of unreserved seats. We can accomplish this with a priority queue.\n\n* Initialize our priority queue in the constructor, also instantiate `seatPointer = 1` to continue iterating up to n if our priority queue is empty\n* If our priority queue `is not` empty, pop first element and return it in our `reserve()` method\n* If our priority queue `is` empty, increment `seatPointer` and return it in our `reserve()` method\n* Finally, push `seatNumber` to our priority queue in our `unreserve(seatNumber)` method\n\n**Complexity**\nTime complexity: O(log n)\nSpace complexity: O(n)\n<br>\n\n```\nimport heapq\nclass SeatManager:\n \n def __init__(self, n: int):\n self.unreserved = []\n heapq.heapify(self.unreserved)\n self.seatPointer = 1\n \n def reserve(self) -> int:\n # pop from unreserved seats\n if len(self.unreserved) > 0:\n output = self.unreserved[0] # grab smallest unreserved seat\n heapq.heappop(self.unreserved)\n \n # \'previous\' unreserved seats empty - grab remaining seats up to n\n else:\n output = self.seatPointer\n self.seatPointer += 1\n \n return output\n\n def unreserve(self, seatNumber: int) -> None:\n # push unreserved seat to priority queue\n heapq.heappush(self.unreserved, seatNumber)\n```\n<br>\n\n**Simple HashMap Solution**\n\nWe need a way to store and track the minimum of this set of unreserved seats. Although not as efficient, this same issue can also be addressed using a HashMap. We follow the same steps as in the priority queue, but to find the minimum of our set of unreserved seats, we instead sort the keys in the map and grab the minimum. \n\n**Complexity**\nTime complexity: O(n)\nSpace complexity: O(n)\n<br>\n\n```\nclass SeatManager:\n \n def __init__(self, n: int):\n self.unreserved = {}\n self.seatPointer = 1\n \n def reserve(self) -> int:\n # grab from unreserved seats\n if len(self.unreserved) > 0:\n output = min(self.unreserved.keys()) # grab smallest unreserved seat\n del self.unreserved[output]\n \n # \'previous\' unreserved seats empty - grab remaining seats up to n\n else:\n output = self.seatPointer\n self.seatPointer += 1\n \n return output\n\n def unreserve(self, seatNumber: int) -> None:\n # populate unreserved seats\n self.unreserved[seatNumber] = 0\n``` | 1 | Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`.
Implement the `SeatManager` class:
* `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available.
* `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number.
* `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`.
**Example 1:**
**Input**
\[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\]
\[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\]
**Output**
\[null, 1, 2, null, 2, 3, 4, 5, null\]
**Explanation**
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\].
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3.
seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4.
seatManager.reserve(); // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\].
**Constraints:**
* `1 <= n <= 105`
* `1 <= seatNumber <= n`
* For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat.
* For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved.
* At most `105` calls **in total** will be made to `reserve` and `unreserve`. | For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix. |
Python | Optimized Min Heap | O(log n) | 99% T 98% S | seat-reservation-manager | 0 | 1 | **Optimized Priority Queue Solution**\n\nOur objective is to reserve and unreserve seats with a set of commands. Ideally we would iterate from 1 to n in order to reserve the inital set of n unreserved seats, and our biggest challenge is reserving seats after a series of seats have been unreserved. We need a way to store and track the minimum of this set of unreserved seats. We can accomplish this with a priority queue.\n\n* Initialize our priority queue in the constructor, also instantiate `seatPointer = 1` to continue iterating up to n if our priority queue is empty\n* If our priority queue `is not` empty, pop first element and return it in our `reserve()` method\n* If our priority queue `is` empty, increment `seatPointer` and return it in our `reserve()` method\n* Finally, push `seatNumber` to our priority queue in our `unreserve(seatNumber)` method\n\n**Complexity**\nTime complexity: O(log n)\nSpace complexity: O(n)\n<br>\n\n```\nimport heapq\nclass SeatManager:\n \n def __init__(self, n: int):\n self.unreserved = []\n heapq.heapify(self.unreserved)\n self.seatPointer = 1\n \n def reserve(self) -> int:\n # pop from unreserved seats\n if len(self.unreserved) > 0:\n output = self.unreserved[0] # grab smallest unreserved seat\n heapq.heappop(self.unreserved)\n \n # \'previous\' unreserved seats empty - grab remaining seats up to n\n else:\n output = self.seatPointer\n self.seatPointer += 1\n \n return output\n\n def unreserve(self, seatNumber: int) -> None:\n # push unreserved seat to priority queue\n heapq.heappush(self.unreserved, seatNumber)\n```\n<br>\n\n**Simple HashMap Solution**\n\nWe need a way to store and track the minimum of this set of unreserved seats. Although not as efficient, this same issue can also be addressed using a HashMap. We follow the same steps as in the priority queue, but to find the minimum of our set of unreserved seats, we instead sort the keys in the map and grab the minimum. \n\n**Complexity**\nTime complexity: O(n)\nSpace complexity: O(n)\n<br>\n\n```\nclass SeatManager:\n \n def __init__(self, n: int):\n self.unreserved = {}\n self.seatPointer = 1\n \n def reserve(self) -> int:\n # grab from unreserved seats\n if len(self.unreserved) > 0:\n output = min(self.unreserved.keys()) # grab smallest unreserved seat\n del self.unreserved[output]\n \n # \'previous\' unreserved seats empty - grab remaining seats up to n\n else:\n output = self.seatPointer\n self.seatPointer += 1\n \n return output\n\n def unreserve(self, seatNumber: int) -> None:\n # populate unreserved seats\n self.unreserved[seatNumber] = 0\n``` | 1 | A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s.
* For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special.
* In contrast, `[2,1,0]`, `[1]`, and `[0,1,2,0]` are not special.
Given an array `nums` (consisting of **only** integers `0`, `1`, and `2`), return _the **number of different subsequences** that are special_. Since the answer may be very large, **return it modulo** `109 + 7`.
A **subsequence** of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are **different** if the **set of indices** chosen are different.
**Example 1:**
**Input:** nums = \[0,1,2,2\]
**Output:** 3
**Explanation:** The special subsequences are bolded \[**0**,**1**,**2**,2\], \[**0**,**1**,2,**2**\], and \[**0**,**1**,**2**,**2**\].
**Example 2:**
**Input:** nums = \[2,2,0,0\]
**Output:** 0
**Explanation:** There are no special subsequences in \[2,2,0,0\].
**Example 3:**
**Input:** nums = \[0,1,2,0,1,2\]
**Output:** 7
**Explanation:** The special subsequences are bolded:
- \[**0**,**1**,**2**,0,1,2\]
- \[**0**,**1**,2,0,1,**2**\]
- \[**0**,**1**,**2**,0,1,**2**\]
- \[**0**,**1**,2,0,**1**,**2**\]
- \[**0**,1,2,**0**,**1**,**2**\]
- \[**0**,1,2,0,**1**,**2**\]
- \[0,1,2,**0**,**1**,**2**\]
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 2` | You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an element, in a reasonable time. Ordered sets support these operations. |
🦅🦀🎃 Efficient Seat Reservation Management: Binary Search vs. Binary Heap | seat-reservation-manager | 0 | 1 | # Intuition\n\nIn my first glance, I thought this is a `Binary Search` problem.\nBut after submitting an AC solution, I discovered other methods that use `Binary Heap`.\n\n# Approach\n\n1. Binary Search\n2. Binary Heap\n3. Binary Heap with checkpoint\n\n# Complexity\n\nM: the maximum number of calls made.\nN: value of `n`.\n\n- Time complexity:\n\n> Binary Search: $$O(M*N)$$\n> Binary Heap: $$O((M+N)*Log(N))$$\n> Binary Heap with checkpoint: $$O(M*Log(N))$$\n\n- Space complexity:\n> $$O(N)$$\n\n# Code\n```rust []\nstruct SeatManager {\n seats: Vec<i32>,\n}\n\n\n/** \n * `&self` means the method takes an immutable reference.\n * If you need a mutable reference, change it to `&mut self` instead.\n */\nimpl SeatManager {\n\n fn new(n: i32) -> Self {\n Self {\n seats: (1..=n).rev().collect(),\n }\n }\n\n fn reserve(&mut self) -> i32 {\n return self.seats.pop().unwrap()\n }\n\n fn unreserve(&mut self, seat_number: i32) {\n let mut left: usize = 0;\n let mut right: usize = self.seats.len();\n while left < right {\n let middle: usize = left + (right - left) / 2;\n if self.seats[middle] < seat_number {\n right = middle;\n } else {\n left = middle + 1;\n }\n }\n\n self.seats.insert(left, seat_number);\n }\n}\n```\n```rust []\nuse std::cmp::Reverse;\nuse std::collections::BinaryHeap;\nstruct SeatManager {\n seats: BinaryHeap<Reverse<i32>>,\n}\n\n\n/** \n * `&self` means the method takes an immutable reference.\n * If you need a mutable reference, change it to `&mut self` instead.\n */\nimpl SeatManager {\n\n fn new(n: i32) -> Self {\n /* Option 1 */\n let mut heap: BinaryHeap<Reverse<i32>> = BinaryHeap::new();\n for value in 1..=n {\n heap.push(Reverse(value));\n }\n Self {\n seats: heap,\n }\n /* Option 2\n\n Self {\n seats: BinaryHeap::from((1..=n).map(|value| Reverse(value)).collect::<Vec<Reverse<i32>>>()),\n }\n */\n }\n\n fn reserve(&mut self) -> i32 {\n /* Option 1 */\n return match self.seats.pop() {\n Some(Reverse(seat)) => seat,\n _ => 0,\n }\n /* Option 2\n\n return self.seats.pop().unwrap().0\n */\n }\n\n fn unreserve(&mut self, seat_number: i32) {\n self.seats.push(Reverse(seat_number));\n }\n}\n```\n```rust []\nuse std::cmp::Reverse;\nuse std::collections::BinaryHeap;\nstruct SeatManager {\n minimum: i32,\n seats: BinaryHeap<Reverse<i32>>,\n}\n\n\n/** \n * `&self` means the method takes an immutable reference.\n * If you need a mutable reference, change it to `&mut self` instead.\n */\nimpl SeatManager {\n\n fn new(n: i32) -> Self {\n Self {\n minimum: 1,\n seats: BinaryHeap::new(),\n }\n }\n\n fn reserve(&mut self) -> i32 {\n if self.seats.is_empty() {\n self.minimum += 1;\n return self.minimum - 1\n }\n\n return self.seats.pop().unwrap().0\n }\n\n fn unreserve(&mut self, seat_number: i32) {\n self.seats.push(Reverse(seat_number));\n }\n}\n```\n```python []\nclass SeatManager:\n\n def __init__(self, n: int):\n self.seats = list(range(n, 0, -1))\n\n def reserve(self) -> int:\n return self.seats.pop()\n\n def unreserve(self, seat_number: int) -> None:\n left = 0\n right = len(self.seats)\n while left < right:\n middle = left + (right-left)//2\n if self.seats[middle] < seat_number:\n right = middle\n else:\n left = middle + 1\n\n # In the worst case, it will have a time complexity of O(N)\n self.seats.insert(left, seat_number)\n```\n```python []\nclass SeatManager:\n\n def __init__(self, n: int):\n self.heap = list(range(1, n+1))\n\n def reserve(self) -> int:\n return heapq.heappop(self.heap)\n\n def unreserve(self, seat_number: int) -> None:\n heapq.heappush(self.heap, seat_number)\n```\n```python []\nclass SeatManager:\n\n def __init__(self, n: int):\n self.minimum = 1\n self.heap = []\n\n def reserve(self) -> int:\n if self.heap:\n return heapq.heappop(self.heap)\n\n self.minimum += 1\n return self.minimum - 1\n\n def unreserve(self, seat_number: int) -> None:\n heapq.heappush(self.heap, seat_number)\n```\n\n## You can find more problem solutions in my Github Repo. I like to use \uD83E\uDD85Python3, \uD83E\uDD80Rust, and \uD83D\uDC18PHP.\n | 1 | Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`.
Implement the `SeatManager` class:
* `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available.
* `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number.
* `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`.
**Example 1:**
**Input**
\[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\]
\[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\]
**Output**
\[null, 1, 2, null, 2, 3, 4, 5, null\]
**Explanation**
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\].
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3.
seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4.
seatManager.reserve(); // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\].
**Constraints:**
* `1 <= n <= 105`
* `1 <= seatNumber <= n`
* For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat.
* For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved.
* At most `105` calls **in total** will be made to `reserve` and `unreserve`. | For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix. |
🦅🦀🎃 Efficient Seat Reservation Management: Binary Search vs. Binary Heap | seat-reservation-manager | 0 | 1 | # Intuition\n\nIn my first glance, I thought this is a `Binary Search` problem.\nBut after submitting an AC solution, I discovered other methods that use `Binary Heap`.\n\n# Approach\n\n1. Binary Search\n2. Binary Heap\n3. Binary Heap with checkpoint\n\n# Complexity\n\nM: the maximum number of calls made.\nN: value of `n`.\n\n- Time complexity:\n\n> Binary Search: $$O(M*N)$$\n> Binary Heap: $$O((M+N)*Log(N))$$\n> Binary Heap with checkpoint: $$O(M*Log(N))$$\n\n- Space complexity:\n> $$O(N)$$\n\n# Code\n```rust []\nstruct SeatManager {\n seats: Vec<i32>,\n}\n\n\n/** \n * `&self` means the method takes an immutable reference.\n * If you need a mutable reference, change it to `&mut self` instead.\n */\nimpl SeatManager {\n\n fn new(n: i32) -> Self {\n Self {\n seats: (1..=n).rev().collect(),\n }\n }\n\n fn reserve(&mut self) -> i32 {\n return self.seats.pop().unwrap()\n }\n\n fn unreserve(&mut self, seat_number: i32) {\n let mut left: usize = 0;\n let mut right: usize = self.seats.len();\n while left < right {\n let middle: usize = left + (right - left) / 2;\n if self.seats[middle] < seat_number {\n right = middle;\n } else {\n left = middle + 1;\n }\n }\n\n self.seats.insert(left, seat_number);\n }\n}\n```\n```rust []\nuse std::cmp::Reverse;\nuse std::collections::BinaryHeap;\nstruct SeatManager {\n seats: BinaryHeap<Reverse<i32>>,\n}\n\n\n/** \n * `&self` means the method takes an immutable reference.\n * If you need a mutable reference, change it to `&mut self` instead.\n */\nimpl SeatManager {\n\n fn new(n: i32) -> Self {\n /* Option 1 */\n let mut heap: BinaryHeap<Reverse<i32>> = BinaryHeap::new();\n for value in 1..=n {\n heap.push(Reverse(value));\n }\n Self {\n seats: heap,\n }\n /* Option 2\n\n Self {\n seats: BinaryHeap::from((1..=n).map(|value| Reverse(value)).collect::<Vec<Reverse<i32>>>()),\n }\n */\n }\n\n fn reserve(&mut self) -> i32 {\n /* Option 1 */\n return match self.seats.pop() {\n Some(Reverse(seat)) => seat,\n _ => 0,\n }\n /* Option 2\n\n return self.seats.pop().unwrap().0\n */\n }\n\n fn unreserve(&mut self, seat_number: i32) {\n self.seats.push(Reverse(seat_number));\n }\n}\n```\n```rust []\nuse std::cmp::Reverse;\nuse std::collections::BinaryHeap;\nstruct SeatManager {\n minimum: i32,\n seats: BinaryHeap<Reverse<i32>>,\n}\n\n\n/** \n * `&self` means the method takes an immutable reference.\n * If you need a mutable reference, change it to `&mut self` instead.\n */\nimpl SeatManager {\n\n fn new(n: i32) -> Self {\n Self {\n minimum: 1,\n seats: BinaryHeap::new(),\n }\n }\n\n fn reserve(&mut self) -> i32 {\n if self.seats.is_empty() {\n self.minimum += 1;\n return self.minimum - 1\n }\n\n return self.seats.pop().unwrap().0\n }\n\n fn unreserve(&mut self, seat_number: i32) {\n self.seats.push(Reverse(seat_number));\n }\n}\n```\n```python []\nclass SeatManager:\n\n def __init__(self, n: int):\n self.seats = list(range(n, 0, -1))\n\n def reserve(self) -> int:\n return self.seats.pop()\n\n def unreserve(self, seat_number: int) -> None:\n left = 0\n right = len(self.seats)\n while left < right:\n middle = left + (right-left)//2\n if self.seats[middle] < seat_number:\n right = middle\n else:\n left = middle + 1\n\n # In the worst case, it will have a time complexity of O(N)\n self.seats.insert(left, seat_number)\n```\n```python []\nclass SeatManager:\n\n def __init__(self, n: int):\n self.heap = list(range(1, n+1))\n\n def reserve(self) -> int:\n return heapq.heappop(self.heap)\n\n def unreserve(self, seat_number: int) -> None:\n heapq.heappush(self.heap, seat_number)\n```\n```python []\nclass SeatManager:\n\n def __init__(self, n: int):\n self.minimum = 1\n self.heap = []\n\n def reserve(self) -> int:\n if self.heap:\n return heapq.heappop(self.heap)\n\n self.minimum += 1\n return self.minimum - 1\n\n def unreserve(self, seat_number: int) -> None:\n heapq.heappush(self.heap, seat_number)\n```\n\n## You can find more problem solutions in my Github Repo. I like to use \uD83E\uDD85Python3, \uD83E\uDD80Rust, and \uD83D\uDC18PHP.\n | 1 | A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s.
* For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special.
* In contrast, `[2,1,0]`, `[1]`, and `[0,1,2,0]` are not special.
Given an array `nums` (consisting of **only** integers `0`, `1`, and `2`), return _the **number of different subsequences** that are special_. Since the answer may be very large, **return it modulo** `109 + 7`.
A **subsequence** of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are **different** if the **set of indices** chosen are different.
**Example 1:**
**Input:** nums = \[0,1,2,2\]
**Output:** 3
**Explanation:** The special subsequences are bolded \[**0**,**1**,**2**,2\], \[**0**,**1**,2,**2**\], and \[**0**,**1**,**2**,**2**\].
**Example 2:**
**Input:** nums = \[2,2,0,0\]
**Output:** 0
**Explanation:** There are no special subsequences in \[2,2,0,0\].
**Example 3:**
**Input:** nums = \[0,1,2,0,1,2\]
**Output:** 7
**Explanation:** The special subsequences are bolded:
- \[**0**,**1**,**2**,0,1,2\]
- \[**0**,**1**,2,0,1,**2**\]
- \[**0**,**1**,**2**,0,1,**2**\]
- \[**0**,**1**,2,0,**1**,**2**\]
- \[**0**,1,2,**0**,**1**,**2**\]
- \[**0**,1,2,0,**1**,**2**\]
- \[0,1,2,**0**,**1**,**2**\]
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 2` | You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an element, in a reasonable time. Ordered sets support these operations. |
【Video】Give me 5 minutes - How we think about a solution | maximum-element-after-decreasing-and-rearranging | 1 | 1 | # Intuition\nSort input array at first.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/1XhaQo-cDVg\n\n\u25A0 Timeline of the video\n\n`0:04` Explain a key point of the question\n`0:19` Important condition\n`0:56` Demonstrate how it works\n`3:08` What if we have a lot of the same numbers in input array?\n`4:10` Coding\n`4:55` Time Complexity and Space Complexity\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,110\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n**My channel reached 3,000 subscribers these days. Thank you so much for your support!**\n\n---\n\n# Approach\n\n## How we think about a solution\n\nWe have 2 types of operations.\n\n**Decrease**\nthe value of any element of arr to a smaller positive integer.\n\n**Rearrange**\nthe elements of arr to be in any order.\n\nSince we cannot increase input numbers, it\'s good idea to sort with ascending order to handle numbers from small to large.\n\n---\n\n\u2B50\uFE0F Points\n\nSort input array to handle numbers from small to large\n\n---\n\nThe description says "The absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, `abs(arr[i] - arr[i - 1]) <= 1`".\n\nBut we don\'t have to care about relation betweeen 2 adjacenet numbers too much because we can decrease any input numbers to smaller positive integer. \n\nAll we have to do is just to find larger number than current number we need.\n\nLet\'s see a concrete example.\n\n```\nInput: arr = [100,3,5,5,1000]\n```\nFirst of all, we sort input array.\n```\n[3,5,5,100,1000]\n```\n\nWe consider the first number(= 3) as 1, because we can decrease the numbers to smaller positive numbers and 1 is minimum possible number, so we can expand possibility to get large max value as a result. Let\'s say `max_val`.\n\nIterate through input numbers one by one.\n```\nindex: 0\n\nreal: [3,5,5,100,1000]\nvirtual: [1,5,5,100,1000]\n\nmax_val = 1\n\n\u203B We don\'t need to create virtual array in the solution code.\nThis is just for visualization.\n```\nAt index 1, what number do we need? it\'s `2`, because we consider index 0(= 3) as `1`, so\n```\nabs(arr[i] - arr[i - 1]) <= 1\nif case 2, abs(2 - 1) <= 1 \u2192 true\nif case 3, abs(3 - 1) <= 1 \u2192 false\n``` \nAt index 1, since we can decrease any large number to smaller positive number. we consider `5` as `2`. \n\nIf current number(= 5) is larger than current `max_val`(= 1), we can decrease `5` to `2`.\n\nSo formula is very simple.\n```\nif arr[i] > max_val:\n max_val += 1\n```\nSo\n```\nif arr[i] > max_val:\nif 5 > 1 \u2192 true\n```\n```\nindex: 1\n\nreal: [3,5,5,100,1000]\nvirtual: [1,2,5,100,1000]\n\nmax_val = 2\n```\n\nI\'ll speed up. At index 2, we need `3`, because current `max_val` is `2`. so\n```\nif arr[i] > max_val:\nif 5 > 2 \u2192 true\n```\n```\nindex: 2\n\nreal: [3,5,5,100,1000]\nvirtual: [1,2,3,100,1000]\n\nmax_val = 3\n```\nAt index 3, we need `4`, so\n```\nif arr[i] > max_val:\nif 100 > 3 \u2192 true\n```\n```\nindex: 3\n\nreal: [3,5,5,100,1000]\nvirtual: [1,2,3,4,1000]\n\nmax_val = 4\n```\nAt index 4, we need `5`, so\n```\nif arr[i] > max_val:\nif 1000 > 4 \u2192 true\n```\n```\nindex: 4\n\nreal: [3,5,5,100,1000]\nvirtual: [1,2,3,4,5]\n\nmax_val = 5\n```\nThis `max_val` should be the maximum possible value of an element in input array after performing operations.\n```\nOutput: 5\n```\n\n### What if we have a lot of the same number in input array?\n\nLet\'s think about this quickly\n\n```\nInput: arr = [1,2,2,2,2]\n```\n```\nindex 0\n\nreal: [1,2,2,2,2]\nvirtual: [1,2,2,2,2]\n\nmax_val = 1\n```\nAt index 1, we need 2\n```\nindex 1\n\nreal: [1,2,2,2,2]\nvirtual: [1,2,2,2,2]\n\nmax_val = 2\n```\nAt index 2 we need 3, but the number at index 2 is smaller than the number we need, so skip.\n```\nindex 2\n\nreal: [1,2,2,2,2]\nvirtual: [1,2,2,2,2]\n\nmax_val = 2\n```\nAt index 3 and 4, it\'s the same as index 2.\n```\nindex 3, index 4\n\nreal: [1,2,2,2,2]\nvirtual: [1,2,2,2,2]\n\nmax_val = 2\n```\n```\nOutput: 2\n```\n\nEasy!\uD83D\uDE04\nLet\'s see a real algorithm!\n\n---\n\n\n### Algorithm Overview:\n\n1. Sort the Array\n2. Iterate Through the Sorted Array\n3. Update Maximum Value\n\n### Detailed Explanation\n\n1. **Sort the Array**:\n ```python\n arr.sort()\n ```\n - The array `arr` is sorted in ascending order using the `sort()` method.\n\n2. **Iterate Through the Sorted Array**:\n ```python\n for i in range(1, len(arr)):\n ```\n - A `for` loop is used to iterate through the array, starting from index 1.\n\n3. **Update Maximum Value**:\n ```python\n if arr[i] > max_val:\n max_val += 1\n ```\n - For each element in the sorted array, if it is greater than the current `max_val`, then `max_val` is incremented by 1.\n\n4. **Return Maximum Value**:\n ```python\n return max_val\n ```\n - The final maximum value is returned as the result.\n\nIn summary, this algorithm ensures that after sorting the array, each element is compared with the current maximum value, and if it is greater, the maximum value is updated. The final maximum value is then returned.\n\n# Complexity\n- Time complexity: $$O(n log n)$$\n\n- Space complexity: $$O(log n)$$ or $$O(n)$$, depends on language you use.\n\n\n```python []\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n max_val = 1\n\n for i in range(1, len(arr)):\n if arr[i] > max_val:\n max_val += 1\n\n return max_val\n```\n```javascript []\nvar maximumElementAfterDecrementingAndRearranging = function(arr) {\n arr.sort((a, b) => a - b);\n let maxVal = 1;\n\n for (let i = 1; i < arr.length; i++) {\n if (arr[i] > maxVal) {\n maxVal += 1;\n }\n }\n\n return maxVal; \n};\n```\n```java []\nclass Solution {\n public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n Arrays.sort(arr);\n int maxVal = 1;\n\n for (int i = 1; i < arr.length; i++) {\n if (arr[i] > maxVal) {\n maxVal += 1;\n }\n }\n\n return maxVal; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {\n sort(arr.begin(), arr.end());\n int maxVal = 1;\n\n for (int i = 1; i < arr.size(); i++) {\n if (arr[i] > maxVal) {\n maxVal += 1;\n }\n }\n\n return maxVal; \n }\n};\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/find-unique-binary-string/solutions/4293749/video-give-me-7-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/tJ_Eu2S4334\n\n\u25A0 Timeline of the video\n\n`0:04` Explain a key point of the question\n`1:39` Why you need to iterate through input array with len(nums) + 1?\n`2:25` Coding\n`3:56` Explain part of my solution code.\n`3:08` What if we have a lot of the same numbers in input array?\n`6:11` Time Complexity and Space Complexity\n\n### My previous daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/unique-length-3-palindromic-subsequences/solutions/4285239/video-give-me-8-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/Tencj59MHAc\n\n\u25A0 Timeline of the video\n\n`0:00` Read the question of Unique Length-3 Palindromic Subsequences\n`1:03` Explain a basic idea to solve Unique Length-3 Palindromic Subsequences\n`4:48` Coding\n`8:01` Summarize the algorithm of Unique Length-3 Palindromic Subsequences\n\n | 44 | You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions:
* The value of the **first** element in `arr` must be `1`.
* The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`.
There are 2 types of operations that you can perform any number of times:
* **Decrease** the value of any element of `arr` to a **smaller positive integer**.
* **Rearrange** the elements of `arr` to be in any order.
Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_.
**Example 1:**
**Input:** arr = \[2,2,1,2,1\]
**Output:** 2
**Explanation:**
We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`.
The largest element in `arr` is 2.
**Example 2:**
**Input:** arr = \[100,1,1000\]
**Output:** 3
**Explanation:**
One possible way to satisfy the conditions is by doing the following:
1. Rearrange `arr` so it becomes `[1,100,1000]`.
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now `arr = [1,2,3], which` satisfies the conditions.
The largest element in `arr is 3.`
**Example 3:**
**Input:** arr = \[1,2,3,4,5\]
**Output:** 5
**Explanation:** The array already satisfies the conditions, and the largest element is 5.
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= arr[i] <= 109` | null |
【Video】Give me 5 minutes - How we think about a solution | maximum-element-after-decreasing-and-rearranging | 1 | 1 | # Intuition\nSort input array at first.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/1XhaQo-cDVg\n\n\u25A0 Timeline of the video\n\n`0:04` Explain a key point of the question\n`0:19` Important condition\n`0:56` Demonstrate how it works\n`3:08` What if we have a lot of the same numbers in input array?\n`4:10` Coding\n`4:55` Time Complexity and Space Complexity\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,110\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n**My channel reached 3,000 subscribers these days. Thank you so much for your support!**\n\n---\n\n# Approach\n\n## How we think about a solution\n\nWe have 2 types of operations.\n\n**Decrease**\nthe value of any element of arr to a smaller positive integer.\n\n**Rearrange**\nthe elements of arr to be in any order.\n\nSince we cannot increase input numbers, it\'s good idea to sort with ascending order to handle numbers from small to large.\n\n---\n\n\u2B50\uFE0F Points\n\nSort input array to handle numbers from small to large\n\n---\n\nThe description says "The absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, `abs(arr[i] - arr[i - 1]) <= 1`".\n\nBut we don\'t have to care about relation betweeen 2 adjacenet numbers too much because we can decrease any input numbers to smaller positive integer. \n\nAll we have to do is just to find larger number than current number we need.\n\nLet\'s see a concrete example.\n\n```\nInput: arr = [100,3,5,5,1000]\n```\nFirst of all, we sort input array.\n```\n[3,5,5,100,1000]\n```\n\nWe consider the first number(= 3) as 1, because we can decrease the numbers to smaller positive numbers and 1 is minimum possible number, so we can expand possibility to get large max value as a result. Let\'s say `max_val`.\n\nIterate through input numbers one by one.\n```\nindex: 0\n\nreal: [3,5,5,100,1000]\nvirtual: [1,5,5,100,1000]\n\nmax_val = 1\n\n\u203B We don\'t need to create virtual array in the solution code.\nThis is just for visualization.\n```\nAt index 1, what number do we need? it\'s `2`, because we consider index 0(= 3) as `1`, so\n```\nabs(arr[i] - arr[i - 1]) <= 1\nif case 2, abs(2 - 1) <= 1 \u2192 true\nif case 3, abs(3 - 1) <= 1 \u2192 false\n``` \nAt index 1, since we can decrease any large number to smaller positive number. we consider `5` as `2`. \n\nIf current number(= 5) is larger than current `max_val`(= 1), we can decrease `5` to `2`.\n\nSo formula is very simple.\n```\nif arr[i] > max_val:\n max_val += 1\n```\nSo\n```\nif arr[i] > max_val:\nif 5 > 1 \u2192 true\n```\n```\nindex: 1\n\nreal: [3,5,5,100,1000]\nvirtual: [1,2,5,100,1000]\n\nmax_val = 2\n```\n\nI\'ll speed up. At index 2, we need `3`, because current `max_val` is `2`. so\n```\nif arr[i] > max_val:\nif 5 > 2 \u2192 true\n```\n```\nindex: 2\n\nreal: [3,5,5,100,1000]\nvirtual: [1,2,3,100,1000]\n\nmax_val = 3\n```\nAt index 3, we need `4`, so\n```\nif arr[i] > max_val:\nif 100 > 3 \u2192 true\n```\n```\nindex: 3\n\nreal: [3,5,5,100,1000]\nvirtual: [1,2,3,4,1000]\n\nmax_val = 4\n```\nAt index 4, we need `5`, so\n```\nif arr[i] > max_val:\nif 1000 > 4 \u2192 true\n```\n```\nindex: 4\n\nreal: [3,5,5,100,1000]\nvirtual: [1,2,3,4,5]\n\nmax_val = 5\n```\nThis `max_val` should be the maximum possible value of an element in input array after performing operations.\n```\nOutput: 5\n```\n\n### What if we have a lot of the same number in input array?\n\nLet\'s think about this quickly\n\n```\nInput: arr = [1,2,2,2,2]\n```\n```\nindex 0\n\nreal: [1,2,2,2,2]\nvirtual: [1,2,2,2,2]\n\nmax_val = 1\n```\nAt index 1, we need 2\n```\nindex 1\n\nreal: [1,2,2,2,2]\nvirtual: [1,2,2,2,2]\n\nmax_val = 2\n```\nAt index 2 we need 3, but the number at index 2 is smaller than the number we need, so skip.\n```\nindex 2\n\nreal: [1,2,2,2,2]\nvirtual: [1,2,2,2,2]\n\nmax_val = 2\n```\nAt index 3 and 4, it\'s the same as index 2.\n```\nindex 3, index 4\n\nreal: [1,2,2,2,2]\nvirtual: [1,2,2,2,2]\n\nmax_val = 2\n```\n```\nOutput: 2\n```\n\nEasy!\uD83D\uDE04\nLet\'s see a real algorithm!\n\n---\n\n\n### Algorithm Overview:\n\n1. Sort the Array\n2. Iterate Through the Sorted Array\n3. Update Maximum Value\n\n### Detailed Explanation\n\n1. **Sort the Array**:\n ```python\n arr.sort()\n ```\n - The array `arr` is sorted in ascending order using the `sort()` method.\n\n2. **Iterate Through the Sorted Array**:\n ```python\n for i in range(1, len(arr)):\n ```\n - A `for` loop is used to iterate through the array, starting from index 1.\n\n3. **Update Maximum Value**:\n ```python\n if arr[i] > max_val:\n max_val += 1\n ```\n - For each element in the sorted array, if it is greater than the current `max_val`, then `max_val` is incremented by 1.\n\n4. **Return Maximum Value**:\n ```python\n return max_val\n ```\n - The final maximum value is returned as the result.\n\nIn summary, this algorithm ensures that after sorting the array, each element is compared with the current maximum value, and if it is greater, the maximum value is updated. The final maximum value is then returned.\n\n# Complexity\n- Time complexity: $$O(n log n)$$\n\n- Space complexity: $$O(log n)$$ or $$O(n)$$, depends on language you use.\n\n\n```python []\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n max_val = 1\n\n for i in range(1, len(arr)):\n if arr[i] > max_val:\n max_val += 1\n\n return max_val\n```\n```javascript []\nvar maximumElementAfterDecrementingAndRearranging = function(arr) {\n arr.sort((a, b) => a - b);\n let maxVal = 1;\n\n for (let i = 1; i < arr.length; i++) {\n if (arr[i] > maxVal) {\n maxVal += 1;\n }\n }\n\n return maxVal; \n};\n```\n```java []\nclass Solution {\n public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n Arrays.sort(arr);\n int maxVal = 1;\n\n for (int i = 1; i < arr.length; i++) {\n if (arr[i] > maxVal) {\n maxVal += 1;\n }\n }\n\n return maxVal; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {\n sort(arr.begin(), arr.end());\n int maxVal = 1;\n\n for (int i = 1; i < arr.size(); i++) {\n if (arr[i] > maxVal) {\n maxVal += 1;\n }\n }\n\n return maxVal; \n }\n};\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/find-unique-binary-string/solutions/4293749/video-give-me-7-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/tJ_Eu2S4334\n\n\u25A0 Timeline of the video\n\n`0:04` Explain a key point of the question\n`1:39` Why you need to iterate through input array with len(nums) + 1?\n`2:25` Coding\n`3:56` Explain part of my solution code.\n`3:08` What if we have a lot of the same numbers in input array?\n`6:11` Time Complexity and Space Complexity\n\n### My previous daily coding challenge post and video.\n\npost\nhttps://leetcode.com/problems/unique-length-3-palindromic-subsequences/solutions/4285239/video-give-me-8-minutes-how-we-think-about-a-solution/\n\nvideo\nhttps://youtu.be/Tencj59MHAc\n\n\u25A0 Timeline of the video\n\n`0:00` Read the question of Unique Length-3 Palindromic Subsequences\n`1:03` Explain a basic idea to solve Unique Length-3 Palindromic Subsequences\n`4:48` Coding\n`8:01` Summarize the algorithm of Unique Length-3 Palindromic Subsequences\n\n | 44 | There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point.
Every day, each cell infected with a virus variant will spread the virus to **all** neighboring points in the **four** cardinal directions (i.e. up, down, left, and right). If a cell has multiple variants, all the variants will spread without interfering with each other.
Given an integer `k`, return _the **minimum integer** number of days for **any** point to contain **at least**_ `k` _of the unique virus variants_.
**Example 1:**
**Input:** points = \[\[1,1\],\[6,1\]\], k = 2
**Output:** 3
**Explanation:** On day 3, points (3,1) and (4,1) will contain both virus variants. Note that these are not the only points that will contain both virus variants.
**Example 2:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 2
**Output:** 2
**Explanation:** On day 2, points (1,3), (2,3), (2,2), and (3,2) will contain the first two viruses. Note that these are not the only points that will contain both virus variants.
**Example 3:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 3
**Output:** 4
**Explanation:** On day 4, the point (5,2) will contain all 3 viruses. Note that this is not the only point that will contain all 3 virus variants.
**Constraints:**
* `n == points.length`
* `2 <= n <= 50`
* `points[i].length == 2`
* `1 <= xi, yi <= 100`
* `2 <= k <= n` | Sort the Array. Decrement each element to the largest integer that satisfies the conditions. |
easy C++/Python sort & loop vs freq count O(n)||30ms beats 100% | maximum-element-after-decreasing-and-rearranging | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSort the `arr` at once.\nSet `arr[0]=1`. Then iterate the `arr`.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInside of the loop just do one thing\n```\nif (arr[i]-arr[i-1]>1)\n arr[i]=arr[i-1]+1;\n```\nAt final\n```\nreturn arr.back()\n```\nHave you ever seen `"[209,209,209,....209]"`? The answer is `210`! strange! I think it should be `209`. I am sure there is no `210` hidden in this array.\nAfter carefully checking there is one `"10000"` hidden in this array.\nProblem solved!\n\nYou can decrease the numbers, sort, must begin with 1, but there is no way to increase the numbers\n# Using frequency count needs only O(n) time\n\nThe maximal value for the answer can not exceed over $n=len(arr)$ (Think about the extreme case `[1,2, 3,..., n]`)\n\nUse a container array `freq` to store the number of occurrencies.\nAdd the count of elements with value i to the accumulated sum. \n`acc += freq[i];`\nIf the accumulated sum exceeds the current value of i, update the accumulated sum to i.\n`\nif (i < acc) \n acc = i;\n`\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n\\log n)->O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n2nd approach $O(n)$.\n# Code C++ runtime 45ms beats 100%\n\n```C++ []\n#pragma GCC optimize("O3")\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) \n {\n sort(arr.begin(), arr.end());\n \n int n=arr.size();\n arr[0]=1;\n #pragma unroll\n for(int i=1; i<n ; i++){\n if (arr[i]-arr[i-1]>1)\n arr[i]=arr[i-1]+1;\n }\n return arr.back();\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```python []\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n ans=1\n for x in arr[1:]:\n ans=min(x, ans+1)\n return ans\n \n```\n# Code using frequency count TC: O(n)\n```\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) \n {\n int freq[100001]={0};\n int n=arr.size();\n #pragma unroll\n for(int& x:arr)\n freq[min(n, x)]++;// if x>n, set x=n\n int acc=0, j=1;\n #pragma unroll\n for(int i=1; i<=n; i++){\n acc += freq[i];\n if (i < acc) \n acc = i;\n }\n return acc;\n }\n};\n```\n\n | 14 | You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions:
* The value of the **first** element in `arr` must be `1`.
* The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`.
There are 2 types of operations that you can perform any number of times:
* **Decrease** the value of any element of `arr` to a **smaller positive integer**.
* **Rearrange** the elements of `arr` to be in any order.
Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_.
**Example 1:**
**Input:** arr = \[2,2,1,2,1\]
**Output:** 2
**Explanation:**
We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`.
The largest element in `arr` is 2.
**Example 2:**
**Input:** arr = \[100,1,1000\]
**Output:** 3
**Explanation:**
One possible way to satisfy the conditions is by doing the following:
1. Rearrange `arr` so it becomes `[1,100,1000]`.
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now `arr = [1,2,3], which` satisfies the conditions.
The largest element in `arr is 3.`
**Example 3:**
**Input:** arr = \[1,2,3,4,5\]
**Output:** 5
**Explanation:** The array already satisfies the conditions, and the largest element is 5.
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= arr[i] <= 109` | null |
easy C++/Python sort & loop vs freq count O(n)||30ms beats 100% | maximum-element-after-decreasing-and-rearranging | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSort the `arr` at once.\nSet `arr[0]=1`. Then iterate the `arr`.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInside of the loop just do one thing\n```\nif (arr[i]-arr[i-1]>1)\n arr[i]=arr[i-1]+1;\n```\nAt final\n```\nreturn arr.back()\n```\nHave you ever seen `"[209,209,209,....209]"`? The answer is `210`! strange! I think it should be `209`. I am sure there is no `210` hidden in this array.\nAfter carefully checking there is one `"10000"` hidden in this array.\nProblem solved!\n\nYou can decrease the numbers, sort, must begin with 1, but there is no way to increase the numbers\n# Using frequency count needs only O(n) time\n\nThe maximal value for the answer can not exceed over $n=len(arr)$ (Think about the extreme case `[1,2, 3,..., n]`)\n\nUse a container array `freq` to store the number of occurrencies.\nAdd the count of elements with value i to the accumulated sum. \n`acc += freq[i];`\nIf the accumulated sum exceeds the current value of i, update the accumulated sum to i.\n`\nif (i < acc) \n acc = i;\n`\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n\\log n)->O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n2nd approach $O(n)$.\n# Code C++ runtime 45ms beats 100%\n\n```C++ []\n#pragma GCC optimize("O3")\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) \n {\n sort(arr.begin(), arr.end());\n \n int n=arr.size();\n arr[0]=1;\n #pragma unroll\n for(int i=1; i<n ; i++){\n if (arr[i]-arr[i-1]>1)\n arr[i]=arr[i-1]+1;\n }\n return arr.back();\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```python []\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n ans=1\n for x in arr[1:]:\n ans=min(x, ans+1)\n return ans\n \n```\n# Code using frequency count TC: O(n)\n```\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) \n {\n int freq[100001]={0};\n int n=arr.size();\n #pragma unroll\n for(int& x:arr)\n freq[min(n, x)]++;// if x>n, set x=n\n int acc=0, j=1;\n #pragma unroll\n for(int i=1; i<=n; i++){\n acc += freq[i];\n if (i < acc) \n acc = i;\n }\n return acc;\n }\n};\n```\n\n | 14 | There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point.
Every day, each cell infected with a virus variant will spread the virus to **all** neighboring points in the **four** cardinal directions (i.e. up, down, left, and right). If a cell has multiple variants, all the variants will spread without interfering with each other.
Given an integer `k`, return _the **minimum integer** number of days for **any** point to contain **at least**_ `k` _of the unique virus variants_.
**Example 1:**
**Input:** points = \[\[1,1\],\[6,1\]\], k = 2
**Output:** 3
**Explanation:** On day 3, points (3,1) and (4,1) will contain both virus variants. Note that these are not the only points that will contain both virus variants.
**Example 2:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 2
**Output:** 2
**Explanation:** On day 2, points (1,3), (2,3), (2,2), and (3,2) will contain the first two viruses. Note that these are not the only points that will contain both virus variants.
**Example 3:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 3
**Output:** 4
**Explanation:** On day 4, the point (5,2) will contain all 3 viruses. Note that this is not the only point that will contain all 3 virus variants.
**Constraints:**
* `n == points.length`
* `2 <= n <= 50`
* `points[i].length == 2`
* `1 <= xi, yi <= 100`
* `2 <= k <= n` | Sort the Array. Decrement each element to the largest integer that satisfies the conditions. |
✅☑[C++/Java/Python/JavaScript] || 3 Approaches || EXPLAINED🔥 | maximum-element-after-decreasing-and-rearranging | 1 | 1 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1 (Greedy)***\n1. **Function Signature:**\n\n - The `maximumElementAfterDecrementingAndRearranging` function takes a reference to a vector of integers as its input argument.\n - It\'s a public member function of a class named `Solution`.\n1. **Sorting the Array:**\n\n - The function starts by sorting the input vector `arr` in ascending order using the `sort()` function from the C++ Standard Library. Sorting the array is essential for the subsequent operations.\n1. **Initializing the Maximum Element (ans):**\n\n - The variable `ans` is initialized to `1`. This variable will store the maximum possible value of an element in the vector after performing the required operations.\n1. **Loop through the Array:**\n\n - A `for` loop is used to iterate through the sorted array `arr`.\n - The loop starts from index `1` (since index `0` is already considered due to initialization of `ans` to `1`).\n1. **Updating ans:**\n\n - Within the loop, it checks if the current element `arr[i]` is greater than or equal to `ans + 1`.\n - If the condition is met (`arr[i] >= ans + 1`), it means the current element can be considered for the next maximum value. Therefore, `ans` is incremented by `1`.\n - This step ensures that after rearranging and decrementing the elements, the maximum possible value that can be achieved for any element is updated in `ans`.\n1. **Return Result:**\n\n - After looping through the array, the function returns the final value stored in `ans`, which represents the maximum possible value of an element in the rearranged vector.\n\n# Complexity\n- *Time complexity:*\n $$O(nlogn)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\n\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {\n sort(arr.begin(), arr.end());\n int ans = 1;\n \n for (int i = 1; i < arr.size(); i++) {\n if (arr[i] >= ans + 1) {\n ans++;\n }\n }\n \n return ans;\n }\n};\n\n```\n```C []\n\nint maximumElementAfterDecrementingAndRearranging(int arr[], int arrSize) {\n // Sorting the array\n for (int i = 0; i < arrSize - 1; i++) {\n for (int j = i + 1; j < arrSize; j++) {\n if (arr[i] > arr[j]) {\n int temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n }\n }\n\n int ans = 1;\n for (int i = 1; i < arrSize; i++) {\n if (arr[i] >= ans + 1) {\n ans++;\n }\n }\n\n return ans;\n}\n\n\n```\n\n```Java []\nclass Solution {\n public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n Arrays.sort(arr);\n int ans = 1;\n \n for (int i = 1; i < arr.length; i++) {\n if (arr[i] >= ans + 1) {\n ans++;\n }\n }\n \n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n ans = 1\n for i in range(1, len(arr)):\n if arr[i] >= ans + 1:\n ans += 1\n\n return ans\n\n\n```\n```javascript []\nfunction maximumElementAfterDecrementingAndRearranging(arr) {\n arr.sort((a, b) => a - b);\n\n let ans = 1;\n for (let i = 1; i < arr.length; i++) {\n if (arr[i] >= ans + 1) {\n ans++;\n }\n }\n\n return ans;\n}\n\n```\n\n---\n#### ***Approach 2 (No Sort)***\n1. **Function Signature:**\n\n - The `maximumElementAfterDecrementingAndRearranging` function takes a reference to a vector of integers as its input argument.\n - It\'s a public member function of a class named `Solution`.\n1. **Initialization:**\n\n - The variable `n` is initialized with the size of the input vector `arr`.\n - A vector counts of size `n + 1` is initialized, where each element is initialized to `0`. This vector will store the count of numbers encountered during iteration.\n1. **Counting Occurrences:**\n\n - The code uses a `for` loop to iterate through each element `num` in the input vector `arr`.\n - For each `num`, the code increments the count at the index `min(num, n)` within the counts vector. This step ensures that counts are kept within the valid range of indices.\n1. **Determining Maximum Value:**\n\n - The variable `ans` is initialized to `1`, which will represent the maximum possible value of an element after rearranging the vector.\n - Another `for` loop runs from `2` to `n` (inclusive).\n - Within this loop, it calculates the updated `ans` value. For each num from 2 to n, it updates ans to the minimum value between the current ans + counts[num] and num.\n - This step ensures that `ans` keeps track of the maximum possible value achievable based on the count of numbers encountered in the input vector.\n1. **Return Result:**\n\n - Finally, the function returns the value stored in `ans`, which represents the maximum possible value of an element in the rearranged vector after performing decrements and rearrangements.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {\n int n = arr.size();\n vector<int> counts = vector(n + 1, 0);\n \n for (int num : arr) {\n counts[min(num, n)]++;\n }\n \n int ans = 1;\n for (int num = 2; num <= n; num++) {\n ans = min(ans + counts[num], num);\n }\n \n return ans;\n }\n};\n\n\n```\n```C []\nint maximumElementAfterDecrementingAndRearranging(int* arr, int arrSize) {\n int n = arrSize;\n int* counts = (int*)calloc(n + 1, sizeof(int));\n \n for (int i = 0; i < n; i++) {\n counts[arr[i] < n ? arr[i] : n]++;\n }\n \n int ans = 1;\n for (int num = 2; num <= n; num++) {\n ans = (ans + counts[num] < num) ? ans + counts[num] : num;\n }\n \n free(counts);\n return ans;\n}\n\n\n```\n\n```Java []\nclass Solution {\n public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n int n = arr.length;\n int[] counts = new int[n + 1];\n \n for (int num : arr) {\n counts[Math.min(num, n)]++;\n }\n \n int ans = 1;\n for (int num = 2; num <= n; num++) {\n ans = Math.min(ans + counts[num], num);\n }\n \n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n n = len(arr)\n counts = [0] * (n + 1)\n \n for num in arr:\n counts[min(num, n)] += 1\n \n ans = 1\n for num in range(2, n + 1):\n ans = min(ans + counts[num], num)\n \n return ans\n\n\n```\n```javascript []\nfunction maximumElementAfterDecrementingAndRearranging(arr) {\n let n = arr.length;\n let counts = Array(n + 1).fill(0);\n \n for (let i = 0; i < n; i++) {\n counts[arr[i] < n ? arr[i] : n]++;\n }\n \n let ans = 1;\n for (let num = 2; num <= n; num++) {\n ans = (ans + counts[num] < num) ? ans + counts[num] : num;\n }\n \n return ans;\n}\n\n```\n\n---\n#### ***Approach 3 (another Greedy approach)***\n1. **Function Signature:**\n\n - The `maximumElementAfterDecrementingAndRearranging` function takes a reference to a vector of integers as its input argument.\n - It\'s a public member function of a class named `Solution`.\n1. **Initialization:**\n\n - The variable `n` is initialized with the size of the input vector `arr`.\n - The input vector `arr` is sorted in ascending order using `std::sort()` from the C++ Standard Library.\n1. **Setting the First Element:**\n\n - The first element of the sorted vector `arr`, `arr[0]`, is explicitly set to `1`. This step likely ensures that the smallest element in the array becomes `1` for further operations.\n1. **Loop Through the Array:**\n\n - The code uses a `for` loop starting from index `1` to traverse the sorted vector `arr`.\n - Within the loop, it checks the absolute difference between the current element `arr[i]` and its previous element `arr[i - 1]`.\n - If the difference is less than or equal to `1`, it implies that the elements are within the allowed range (i.e., consecutive or the same). In such cases, the loop continues to the next iteration without making any changes to the current element.\n - If the difference is greater than `1`, it means the elements are not consecutive. In this case, it sets the current element `arr[i]` to be one more than the previous element `arr[i - 1]`. This step ensures that elements are arranged in a consecutive manner.\n1. **Return Result:**\n\n - After looping through the array and updating the elements as needed, the function returns the value stored in `arr[n - 1]`, which represents the maximum possible value of an element in the rearranged vector after performing decrements and rearrangements.\n\n# Complexity\n- *Time complexity:*\n $$O(nlogn)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {\n \n int n = arr.size();\n sort(arr.begin(), arr.end());\n\n arr[0]=1;\n\n for (int i = 1; i < n; i++) {\n if ( abs(arr[i] - arr[i - 1]) <= 1)continue;\n else arr[i] = arr[i-1] + 1;\n \n }\n\n return arr[n-1];\n\n }\n};\n\n\n```\n```C []\n\nint maximumElementAfterDecrementingAndRearranging(int arr[], int n) {\n qsort(arr, n, sizeof(int), compare); // Assuming compare function sorts in ascending order\n\n arr[0] = 1;\n\n for (int i = 1; i < n; i++) {\n if (abs(arr[i] - arr[i - 1]) <= 1) continue;\n else arr[i] = arr[i - 1] + 1;\n }\n\n return arr[n - 1];\n}\n\n\n```\n\n```Java []\n\n\nclass Solution {\n public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n int n = arr.length;\n Arrays.sort(arr);\n\n arr[0] = 1;\n\n for (int i = 1; i < n; i++) {\n if (Math.abs(arr[i] - arr[i - 1]) <= 1) continue;\n else arr[i] = arr[i - 1] + 1;\n }\n\n return arr[n - 1];\n }\n}\n\n\n\n```\n```python3 []\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr):\n n = len(arr)\n arr.sort()\n\n arr[0] = 1\n\n for i in range(1, n):\n if abs(arr[i] - arr[i - 1]) <= 1:\n continue\n else:\n arr[i] = arr[i - 1] + 1\n\n return arr[n - 1]\n\n\n\n```\n```javascript []\nfunction maximumElementAfterDecrementingAndRearranging(arr) {\n arr.sort((a, b) => a - b);\n\n arr[0] = 1;\n\n for (let i = 1; i < arr.length; i++) {\n if (Math.abs(arr[i] - arr[i - 1]) <= 1) continue;\n else arr[i] = arr[i - 1] + 1;\n }\n\n return arr[arr.length - 1];\n}\n\n\n```\n\n---\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n--- | 4 | You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions:
* The value of the **first** element in `arr` must be `1`.
* The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`.
There are 2 types of operations that you can perform any number of times:
* **Decrease** the value of any element of `arr` to a **smaller positive integer**.
* **Rearrange** the elements of `arr` to be in any order.
Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_.
**Example 1:**
**Input:** arr = \[2,2,1,2,1\]
**Output:** 2
**Explanation:**
We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`.
The largest element in `arr` is 2.
**Example 2:**
**Input:** arr = \[100,1,1000\]
**Output:** 3
**Explanation:**
One possible way to satisfy the conditions is by doing the following:
1. Rearrange `arr` so it becomes `[1,100,1000]`.
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now `arr = [1,2,3], which` satisfies the conditions.
The largest element in `arr is 3.`
**Example 3:**
**Input:** arr = \[1,2,3,4,5\]
**Output:** 5
**Explanation:** The array already satisfies the conditions, and the largest element is 5.
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= arr[i] <= 109` | null |
✅☑[C++/Java/Python/JavaScript] || 3 Approaches || EXPLAINED🔥 | maximum-element-after-decreasing-and-rearranging | 1 | 1 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1 (Greedy)***\n1. **Function Signature:**\n\n - The `maximumElementAfterDecrementingAndRearranging` function takes a reference to a vector of integers as its input argument.\n - It\'s a public member function of a class named `Solution`.\n1. **Sorting the Array:**\n\n - The function starts by sorting the input vector `arr` in ascending order using the `sort()` function from the C++ Standard Library. Sorting the array is essential for the subsequent operations.\n1. **Initializing the Maximum Element (ans):**\n\n - The variable `ans` is initialized to `1`. This variable will store the maximum possible value of an element in the vector after performing the required operations.\n1. **Loop through the Array:**\n\n - A `for` loop is used to iterate through the sorted array `arr`.\n - The loop starts from index `1` (since index `0` is already considered due to initialization of `ans` to `1`).\n1. **Updating ans:**\n\n - Within the loop, it checks if the current element `arr[i]` is greater than or equal to `ans + 1`.\n - If the condition is met (`arr[i] >= ans + 1`), it means the current element can be considered for the next maximum value. Therefore, `ans` is incremented by `1`.\n - This step ensures that after rearranging and decrementing the elements, the maximum possible value that can be achieved for any element is updated in `ans`.\n1. **Return Result:**\n\n - After looping through the array, the function returns the final value stored in `ans`, which represents the maximum possible value of an element in the rearranged vector.\n\n# Complexity\n- *Time complexity:*\n $$O(nlogn)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\n\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {\n sort(arr.begin(), arr.end());\n int ans = 1;\n \n for (int i = 1; i < arr.size(); i++) {\n if (arr[i] >= ans + 1) {\n ans++;\n }\n }\n \n return ans;\n }\n};\n\n```\n```C []\n\nint maximumElementAfterDecrementingAndRearranging(int arr[], int arrSize) {\n // Sorting the array\n for (int i = 0; i < arrSize - 1; i++) {\n for (int j = i + 1; j < arrSize; j++) {\n if (arr[i] > arr[j]) {\n int temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n }\n }\n\n int ans = 1;\n for (int i = 1; i < arrSize; i++) {\n if (arr[i] >= ans + 1) {\n ans++;\n }\n }\n\n return ans;\n}\n\n\n```\n\n```Java []\nclass Solution {\n public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n Arrays.sort(arr);\n int ans = 1;\n \n for (int i = 1; i < arr.length; i++) {\n if (arr[i] >= ans + 1) {\n ans++;\n }\n }\n \n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n ans = 1\n for i in range(1, len(arr)):\n if arr[i] >= ans + 1:\n ans += 1\n\n return ans\n\n\n```\n```javascript []\nfunction maximumElementAfterDecrementingAndRearranging(arr) {\n arr.sort((a, b) => a - b);\n\n let ans = 1;\n for (let i = 1; i < arr.length; i++) {\n if (arr[i] >= ans + 1) {\n ans++;\n }\n }\n\n return ans;\n}\n\n```\n\n---\n#### ***Approach 2 (No Sort)***\n1. **Function Signature:**\n\n - The `maximumElementAfterDecrementingAndRearranging` function takes a reference to a vector of integers as its input argument.\n - It\'s a public member function of a class named `Solution`.\n1. **Initialization:**\n\n - The variable `n` is initialized with the size of the input vector `arr`.\n - A vector counts of size `n + 1` is initialized, where each element is initialized to `0`. This vector will store the count of numbers encountered during iteration.\n1. **Counting Occurrences:**\n\n - The code uses a `for` loop to iterate through each element `num` in the input vector `arr`.\n - For each `num`, the code increments the count at the index `min(num, n)` within the counts vector. This step ensures that counts are kept within the valid range of indices.\n1. **Determining Maximum Value:**\n\n - The variable `ans` is initialized to `1`, which will represent the maximum possible value of an element after rearranging the vector.\n - Another `for` loop runs from `2` to `n` (inclusive).\n - Within this loop, it calculates the updated `ans` value. For each num from 2 to n, it updates ans to the minimum value between the current ans + counts[num] and num.\n - This step ensures that `ans` keeps track of the maximum possible value achievable based on the count of numbers encountered in the input vector.\n1. **Return Result:**\n\n - Finally, the function returns the value stored in `ans`, which represents the maximum possible value of an element in the rearranged vector after performing decrements and rearrangements.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {\n int n = arr.size();\n vector<int> counts = vector(n + 1, 0);\n \n for (int num : arr) {\n counts[min(num, n)]++;\n }\n \n int ans = 1;\n for (int num = 2; num <= n; num++) {\n ans = min(ans + counts[num], num);\n }\n \n return ans;\n }\n};\n\n\n```\n```C []\nint maximumElementAfterDecrementingAndRearranging(int* arr, int arrSize) {\n int n = arrSize;\n int* counts = (int*)calloc(n + 1, sizeof(int));\n \n for (int i = 0; i < n; i++) {\n counts[arr[i] < n ? arr[i] : n]++;\n }\n \n int ans = 1;\n for (int num = 2; num <= n; num++) {\n ans = (ans + counts[num] < num) ? ans + counts[num] : num;\n }\n \n free(counts);\n return ans;\n}\n\n\n```\n\n```Java []\nclass Solution {\n public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n int n = arr.length;\n int[] counts = new int[n + 1];\n \n for (int num : arr) {\n counts[Math.min(num, n)]++;\n }\n \n int ans = 1;\n for (int num = 2; num <= n; num++) {\n ans = Math.min(ans + counts[num], num);\n }\n \n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n n = len(arr)\n counts = [0] * (n + 1)\n \n for num in arr:\n counts[min(num, n)] += 1\n \n ans = 1\n for num in range(2, n + 1):\n ans = min(ans + counts[num], num)\n \n return ans\n\n\n```\n```javascript []\nfunction maximumElementAfterDecrementingAndRearranging(arr) {\n let n = arr.length;\n let counts = Array(n + 1).fill(0);\n \n for (let i = 0; i < n; i++) {\n counts[arr[i] < n ? arr[i] : n]++;\n }\n \n let ans = 1;\n for (let num = 2; num <= n; num++) {\n ans = (ans + counts[num] < num) ? ans + counts[num] : num;\n }\n \n return ans;\n}\n\n```\n\n---\n#### ***Approach 3 (another Greedy approach)***\n1. **Function Signature:**\n\n - The `maximumElementAfterDecrementingAndRearranging` function takes a reference to a vector of integers as its input argument.\n - It\'s a public member function of a class named `Solution`.\n1. **Initialization:**\n\n - The variable `n` is initialized with the size of the input vector `arr`.\n - The input vector `arr` is sorted in ascending order using `std::sort()` from the C++ Standard Library.\n1. **Setting the First Element:**\n\n - The first element of the sorted vector `arr`, `arr[0]`, is explicitly set to `1`. This step likely ensures that the smallest element in the array becomes `1` for further operations.\n1. **Loop Through the Array:**\n\n - The code uses a `for` loop starting from index `1` to traverse the sorted vector `arr`.\n - Within the loop, it checks the absolute difference between the current element `arr[i]` and its previous element `arr[i - 1]`.\n - If the difference is less than or equal to `1`, it implies that the elements are within the allowed range (i.e., consecutive or the same). In such cases, the loop continues to the next iteration without making any changes to the current element.\n - If the difference is greater than `1`, it means the elements are not consecutive. In this case, it sets the current element `arr[i]` to be one more than the previous element `arr[i - 1]`. This step ensures that elements are arranged in a consecutive manner.\n1. **Return Result:**\n\n - After looping through the array and updating the elements as needed, the function returns the value stored in `arr[n - 1]`, which represents the maximum possible value of an element in the rearranged vector after performing decrements and rearrangements.\n\n# Complexity\n- *Time complexity:*\n $$O(nlogn)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {\n \n int n = arr.size();\n sort(arr.begin(), arr.end());\n\n arr[0]=1;\n\n for (int i = 1; i < n; i++) {\n if ( abs(arr[i] - arr[i - 1]) <= 1)continue;\n else arr[i] = arr[i-1] + 1;\n \n }\n\n return arr[n-1];\n\n }\n};\n\n\n```\n```C []\n\nint maximumElementAfterDecrementingAndRearranging(int arr[], int n) {\n qsort(arr, n, sizeof(int), compare); // Assuming compare function sorts in ascending order\n\n arr[0] = 1;\n\n for (int i = 1; i < n; i++) {\n if (abs(arr[i] - arr[i - 1]) <= 1) continue;\n else arr[i] = arr[i - 1] + 1;\n }\n\n return arr[n - 1];\n}\n\n\n```\n\n```Java []\n\n\nclass Solution {\n public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n int n = arr.length;\n Arrays.sort(arr);\n\n arr[0] = 1;\n\n for (int i = 1; i < n; i++) {\n if (Math.abs(arr[i] - arr[i - 1]) <= 1) continue;\n else arr[i] = arr[i - 1] + 1;\n }\n\n return arr[n - 1];\n }\n}\n\n\n\n```\n```python3 []\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr):\n n = len(arr)\n arr.sort()\n\n arr[0] = 1\n\n for i in range(1, n):\n if abs(arr[i] - arr[i - 1]) <= 1:\n continue\n else:\n arr[i] = arr[i - 1] + 1\n\n return arr[n - 1]\n\n\n\n```\n```javascript []\nfunction maximumElementAfterDecrementingAndRearranging(arr) {\n arr.sort((a, b) => a - b);\n\n arr[0] = 1;\n\n for (let i = 1; i < arr.length; i++) {\n if (Math.abs(arr[i] - arr[i - 1]) <= 1) continue;\n else arr[i] = arr[i - 1] + 1;\n }\n\n return arr[arr.length - 1];\n}\n\n\n```\n\n---\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n--- | 4 | There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point.
Every day, each cell infected with a virus variant will spread the virus to **all** neighboring points in the **four** cardinal directions (i.e. up, down, left, and right). If a cell has multiple variants, all the variants will spread without interfering with each other.
Given an integer `k`, return _the **minimum integer** number of days for **any** point to contain **at least**_ `k` _of the unique virus variants_.
**Example 1:**
**Input:** points = \[\[1,1\],\[6,1\]\], k = 2
**Output:** 3
**Explanation:** On day 3, points (3,1) and (4,1) will contain both virus variants. Note that these are not the only points that will contain both virus variants.
**Example 2:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 2
**Output:** 2
**Explanation:** On day 2, points (1,3), (2,3), (2,2), and (3,2) will contain the first two viruses. Note that these are not the only points that will contain both virus variants.
**Example 3:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 3
**Output:** 4
**Explanation:** On day 4, the point (5,2) will contain all 3 viruses. Note that this is not the only point that will contain all 3 virus variants.
**Constraints:**
* `n == points.length`
* `2 <= n <= 50`
* `points[i].length == 2`
* `1 <= xi, yi <= 100`
* `2 <= k <= n` | Sort the Array. Decrement each element to the largest integer that satisfies the conditions. |
🥇 C++ | PYTHON | JAVA || EXPLAINED || ; ] ✅ | maximum-element-after-decreasing-and-rearranging | 1 | 1 | \n**UPVOTE IF HELPFuuL**\n\n# Key Points\n- First element is always ```1```\n- Array is always ascending [ increasing order ]\n- Element equal or greater than ```1``` is possible in final array from previous element.\n\n\n# Approach\nIt is defined that the first element always remains one and array is sorted in ascending manner.\nAlso the next element cannot be greater than ```1``` more than its previous element.\nAlso to minimise the number of ```decreasing``` operations we need to keep the element as ```MAX``` as possible.\n - If element is equal to its predessor -> ```a[i] == a[i-1]```, then no decrement is required.\n - Else we perform decreament operations, such that ```a[i] == a[i-1] + 1```\n\nNow we only need the last value of this sorted array, which can be stored using a variable.\nBelow is implementation of this logic.\n\n# Complexity\n- Time complexity: O(N * logN)\nN log N -> foor sorting\n\n- Space complexity: O(1) -> Constant Extra space required\n\n\n**UPVOTE IF HELPFuuL**\n\n```C++ []\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {\n sort(arr.begin(),arr.end());\n int res = 1;\n for(int i=1; i<arr.size(); i++){\n if(arr[i] > res)\n res = res + 1;\n }\n return res;\n }\n};\n```\n```python []\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n res = 1\n for i in range(1,len(arr)):\n if (arr[i] > res):\n res += 1\n return res\n```\n```JAVA []\nclass Solution {\n public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n Arrays.sort(arr);\n int res = 1;\n for (int i = 1; i < arr.length; ++i) {\n if (arr[i] > res) {\n ++res;\n }\n }\n return res;\n }\n}\n```\n\n\n\n | 29 | You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions:
* The value of the **first** element in `arr` must be `1`.
* The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`.
There are 2 types of operations that you can perform any number of times:
* **Decrease** the value of any element of `arr` to a **smaller positive integer**.
* **Rearrange** the elements of `arr` to be in any order.
Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_.
**Example 1:**
**Input:** arr = \[2,2,1,2,1\]
**Output:** 2
**Explanation:**
We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`.
The largest element in `arr` is 2.
**Example 2:**
**Input:** arr = \[100,1,1000\]
**Output:** 3
**Explanation:**
One possible way to satisfy the conditions is by doing the following:
1. Rearrange `arr` so it becomes `[1,100,1000]`.
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now `arr = [1,2,3], which` satisfies the conditions.
The largest element in `arr is 3.`
**Example 3:**
**Input:** arr = \[1,2,3,4,5\]
**Output:** 5
**Explanation:** The array already satisfies the conditions, and the largest element is 5.
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= arr[i] <= 109` | null |
🥇 C++ | PYTHON | JAVA || EXPLAINED || ; ] ✅ | maximum-element-after-decreasing-and-rearranging | 1 | 1 | \n**UPVOTE IF HELPFuuL**\n\n# Key Points\n- First element is always ```1```\n- Array is always ascending [ increasing order ]\n- Element equal or greater than ```1``` is possible in final array from previous element.\n\n\n# Approach\nIt is defined that the first element always remains one and array is sorted in ascending manner.\nAlso the next element cannot be greater than ```1``` more than its previous element.\nAlso to minimise the number of ```decreasing``` operations we need to keep the element as ```MAX``` as possible.\n - If element is equal to its predessor -> ```a[i] == a[i-1]```, then no decrement is required.\n - Else we perform decreament operations, such that ```a[i] == a[i-1] + 1```\n\nNow we only need the last value of this sorted array, which can be stored using a variable.\nBelow is implementation of this logic.\n\n# Complexity\n- Time complexity: O(N * logN)\nN log N -> foor sorting\n\n- Space complexity: O(1) -> Constant Extra space required\n\n\n**UPVOTE IF HELPFuuL**\n\n```C++ []\nclass Solution {\npublic:\n int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {\n sort(arr.begin(),arr.end());\n int res = 1;\n for(int i=1; i<arr.size(); i++){\n if(arr[i] > res)\n res = res + 1;\n }\n return res;\n }\n};\n```\n```python []\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n res = 1\n for i in range(1,len(arr)):\n if (arr[i] > res):\n res += 1\n return res\n```\n```JAVA []\nclass Solution {\n public int maximumElementAfterDecrementingAndRearranging(int[] arr) {\n Arrays.sort(arr);\n int res = 1;\n for (int i = 1; i < arr.length; ++i) {\n if (arr[i] > res) {\n ++res;\n }\n }\n return res;\n }\n}\n```\n\n\n\n | 29 | There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point.
Every day, each cell infected with a virus variant will spread the virus to **all** neighboring points in the **four** cardinal directions (i.e. up, down, left, and right). If a cell has multiple variants, all the variants will spread without interfering with each other.
Given an integer `k`, return _the **minimum integer** number of days for **any** point to contain **at least**_ `k` _of the unique virus variants_.
**Example 1:**
**Input:** points = \[\[1,1\],\[6,1\]\], k = 2
**Output:** 3
**Explanation:** On day 3, points (3,1) and (4,1) will contain both virus variants. Note that these are not the only points that will contain both virus variants.
**Example 2:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 2
**Output:** 2
**Explanation:** On day 2, points (1,3), (2,3), (2,2), and (3,2) will contain the first two viruses. Note that these are not the only points that will contain both virus variants.
**Example 3:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 3
**Output:** 4
**Explanation:** On day 4, the point (5,2) will contain all 3 viruses. Note that this is not the only point that will contain all 3 virus variants.
**Constraints:**
* `n == points.length`
* `2 <= n <= 50`
* `points[i].length == 2`
* `1 <= xi, yi <= 100`
* `2 <= k <= n` | Sort the Array. Decrement each element to the largest integer that satisfies the conditions. |
✅ One Line Solution | maximum-element-after-decreasing-and-rearranging | 0 | 1 | # Complexity\n- Time complexity: $$O(n*log(n))$$.\n\n- Space complexity: $$O(n)$$.\n\n# Code #1 - Oneliner\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n return reduce(lambda r, n: min(r + 1, n), sorted(arr)[1:], 1)\n```\n# Code #2 - Oneliner\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n return ([prev:=1] + [prev:=min(prev + 1, num) for num in sorted(arr)[1:]])[-1]\n```\n\n# Code #2.1 - Unwrapped\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n prev = 1\n for num in sorted(arr)[1:]:\n prev = min(prev + 1, num)\n \n return prev\n``` | 2 | You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions:
* The value of the **first** element in `arr` must be `1`.
* The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`.
There are 2 types of operations that you can perform any number of times:
* **Decrease** the value of any element of `arr` to a **smaller positive integer**.
* **Rearrange** the elements of `arr` to be in any order.
Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_.
**Example 1:**
**Input:** arr = \[2,2,1,2,1\]
**Output:** 2
**Explanation:**
We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`.
The largest element in `arr` is 2.
**Example 2:**
**Input:** arr = \[100,1,1000\]
**Output:** 3
**Explanation:**
One possible way to satisfy the conditions is by doing the following:
1. Rearrange `arr` so it becomes `[1,100,1000]`.
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now `arr = [1,2,3], which` satisfies the conditions.
The largest element in `arr is 3.`
**Example 3:**
**Input:** arr = \[1,2,3,4,5\]
**Output:** 5
**Explanation:** The array already satisfies the conditions, and the largest element is 5.
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= arr[i] <= 109` | null |
✅ One Line Solution | maximum-element-after-decreasing-and-rearranging | 0 | 1 | # Complexity\n- Time complexity: $$O(n*log(n))$$.\n\n- Space complexity: $$O(n)$$.\n\n# Code #1 - Oneliner\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n return reduce(lambda r, n: min(r + 1, n), sorted(arr)[1:], 1)\n```\n# Code #2 - Oneliner\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n return ([prev:=1] + [prev:=min(prev + 1, num) for num in sorted(arr)[1:]])[-1]\n```\n\n# Code #2.1 - Unwrapped\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n prev = 1\n for num in sorted(arr)[1:]:\n prev = min(prev + 1, num)\n \n return prev\n``` | 2 | There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point.
Every day, each cell infected with a virus variant will spread the virus to **all** neighboring points in the **four** cardinal directions (i.e. up, down, left, and right). If a cell has multiple variants, all the variants will spread without interfering with each other.
Given an integer `k`, return _the **minimum integer** number of days for **any** point to contain **at least**_ `k` _of the unique virus variants_.
**Example 1:**
**Input:** points = \[\[1,1\],\[6,1\]\], k = 2
**Output:** 3
**Explanation:** On day 3, points (3,1) and (4,1) will contain both virus variants. Note that these are not the only points that will contain both virus variants.
**Example 2:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 2
**Output:** 2
**Explanation:** On day 2, points (1,3), (2,3), (2,2), and (3,2) will contain the first two viruses. Note that these are not the only points that will contain both virus variants.
**Example 3:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 3
**Output:** 4
**Explanation:** On day 4, the point (5,2) will contain all 3 viruses. Note that this is not the only point that will contain all 3 virus variants.
**Constraints:**
* `n == points.length`
* `2 <= n <= 50`
* `points[i].length == 2`
* `1 <= xi, yi <= 100`
* `2 <= k <= n` | Sort the Array. Decrement each element to the largest integer that satisfies the conditions. |
Intuitive sorting approach with comments!😸 | maximum-element-after-decreasing-and-rearranging | 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)$$ --> O(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1)\n\n# Code\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort() #sort to make consecutive elements nearby \n arr[0] = 1 \n for i in range(1 , len(arr)):\n if abs(arr[i] - arr[i-1])<=1: #already satisfies the condition\n continue \n else:\n arr[i] = arr[i-1] + 1 #since we want to maximize the largest element (being greedy here!)\n return arr[-1]\n``` | 2 | You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions:
* The value of the **first** element in `arr` must be `1`.
* The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`.
There are 2 types of operations that you can perform any number of times:
* **Decrease** the value of any element of `arr` to a **smaller positive integer**.
* **Rearrange** the elements of `arr` to be in any order.
Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_.
**Example 1:**
**Input:** arr = \[2,2,1,2,1\]
**Output:** 2
**Explanation:**
We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`.
The largest element in `arr` is 2.
**Example 2:**
**Input:** arr = \[100,1,1000\]
**Output:** 3
**Explanation:**
One possible way to satisfy the conditions is by doing the following:
1. Rearrange `arr` so it becomes `[1,100,1000]`.
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now `arr = [1,2,3], which` satisfies the conditions.
The largest element in `arr is 3.`
**Example 3:**
**Input:** arr = \[1,2,3,4,5\]
**Output:** 5
**Explanation:** The array already satisfies the conditions, and the largest element is 5.
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= arr[i] <= 109` | null |
Intuitive sorting approach with comments!😸 | maximum-element-after-decreasing-and-rearranging | 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)$$ --> O(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1)\n\n# Code\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort() #sort to make consecutive elements nearby \n arr[0] = 1 \n for i in range(1 , len(arr)):\n if abs(arr[i] - arr[i-1])<=1: #already satisfies the condition\n continue \n else:\n arr[i] = arr[i-1] + 1 #since we want to maximize the largest element (being greedy here!)\n return arr[-1]\n``` | 2 | There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point.
Every day, each cell infected with a virus variant will spread the virus to **all** neighboring points in the **four** cardinal directions (i.e. up, down, left, and right). If a cell has multiple variants, all the variants will spread without interfering with each other.
Given an integer `k`, return _the **minimum integer** number of days for **any** point to contain **at least**_ `k` _of the unique virus variants_.
**Example 1:**
**Input:** points = \[\[1,1\],\[6,1\]\], k = 2
**Output:** 3
**Explanation:** On day 3, points (3,1) and (4,1) will contain both virus variants. Note that these are not the only points that will contain both virus variants.
**Example 2:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 2
**Output:** 2
**Explanation:** On day 2, points (1,3), (2,3), (2,2), and (3,2) will contain the first two viruses. Note that these are not the only points that will contain both virus variants.
**Example 3:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 3
**Output:** 4
**Explanation:** On day 4, the point (5,2) will contain all 3 viruses. Note that this is not the only point that will contain all 3 virus variants.
**Constraints:**
* `n == points.length`
* `2 <= n <= 50`
* `points[i].length == 2`
* `1 <= xi, yi <= 100`
* `2 <= k <= n` | Sort the Array. Decrement each element to the largest integer that satisfies the conditions. |
A somewhat elegant approach | maximum-element-after-decreasing-and-rearranging | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach can be broken down in a few steps:\n>sort the array\n>make the first element 1(in some edge cases it might not be)\n>run a for loop that will change the elemnts if the difference is more than 1\n>return the last element\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# Code\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n n=len(arr)\n arr.sort()\n arr[0]=1\n for i in range (n-1):\n if abs(arr[i]-arr[i+1])>1:\n arr[i+1]=arr[i]+1\n return arr[n-1]\n \n``` | 1 | You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions:
* The value of the **first** element in `arr` must be `1`.
* The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`.
There are 2 types of operations that you can perform any number of times:
* **Decrease** the value of any element of `arr` to a **smaller positive integer**.
* **Rearrange** the elements of `arr` to be in any order.
Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_.
**Example 1:**
**Input:** arr = \[2,2,1,2,1\]
**Output:** 2
**Explanation:**
We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`.
The largest element in `arr` is 2.
**Example 2:**
**Input:** arr = \[100,1,1000\]
**Output:** 3
**Explanation:**
One possible way to satisfy the conditions is by doing the following:
1. Rearrange `arr` so it becomes `[1,100,1000]`.
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now `arr = [1,2,3], which` satisfies the conditions.
The largest element in `arr is 3.`
**Example 3:**
**Input:** arr = \[1,2,3,4,5\]
**Output:** 5
**Explanation:** The array already satisfies the conditions, and the largest element is 5.
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= arr[i] <= 109` | null |
A somewhat elegant approach | maximum-element-after-decreasing-and-rearranging | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach can be broken down in a few steps:\n>sort the array\n>make the first element 1(in some edge cases it might not be)\n>run a for loop that will change the elemnts if the difference is more than 1\n>return the last element\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# Code\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n n=len(arr)\n arr.sort()\n arr[0]=1\n for i in range (n-1):\n if abs(arr[i]-arr[i+1])>1:\n arr[i+1]=arr[i]+1\n return arr[n-1]\n \n``` | 1 | There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point.
Every day, each cell infected with a virus variant will spread the virus to **all** neighboring points in the **four** cardinal directions (i.e. up, down, left, and right). If a cell has multiple variants, all the variants will spread without interfering with each other.
Given an integer `k`, return _the **minimum integer** number of days for **any** point to contain **at least**_ `k` _of the unique virus variants_.
**Example 1:**
**Input:** points = \[\[1,1\],\[6,1\]\], k = 2
**Output:** 3
**Explanation:** On day 3, points (3,1) and (4,1) will contain both virus variants. Note that these are not the only points that will contain both virus variants.
**Example 2:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 2
**Output:** 2
**Explanation:** On day 2, points (1,3), (2,3), (2,2), and (3,2) will contain the first two viruses. Note that these are not the only points that will contain both virus variants.
**Example 3:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 3
**Output:** 4
**Explanation:** On day 4, the point (5,2) will contain all 3 viruses. Note that this is not the only point that will contain all 3 virus variants.
**Constraints:**
* `n == points.length`
* `2 <= n <= 50`
* `points[i].length == 2`
* `1 <= xi, yi <= 100`
* `2 <= k <= n` | Sort the Array. Decrement each element to the largest integer that satisfies the conditions. |
Easy-Sort.py | maximum-element-after-decreasing-and-rearranging | 0 | 1 | # Complexity\n- Time complexity:\n $$O(N\'logN )$$\n\n- Space complexity:\n $$O(1)$$\n\n# Code\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n arr[0]=1\n for i in range(1,len(arr)):\n if arr[i]-arr[i-1]>1:arr[i]=arr[i-1]+1\n return arr[-1]\n``` | 8 | You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions:
* The value of the **first** element in `arr` must be `1`.
* The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`.
There are 2 types of operations that you can perform any number of times:
* **Decrease** the value of any element of `arr` to a **smaller positive integer**.
* **Rearrange** the elements of `arr` to be in any order.
Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_.
**Example 1:**
**Input:** arr = \[2,2,1,2,1\]
**Output:** 2
**Explanation:**
We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`.
The largest element in `arr` is 2.
**Example 2:**
**Input:** arr = \[100,1,1000\]
**Output:** 3
**Explanation:**
One possible way to satisfy the conditions is by doing the following:
1. Rearrange `arr` so it becomes `[1,100,1000]`.
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now `arr = [1,2,3], which` satisfies the conditions.
The largest element in `arr is 3.`
**Example 3:**
**Input:** arr = \[1,2,3,4,5\]
**Output:** 5
**Explanation:** The array already satisfies the conditions, and the largest element is 5.
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= arr[i] <= 109` | null |
Easy-Sort.py | maximum-element-after-decreasing-and-rearranging | 0 | 1 | # Complexity\n- Time complexity:\n $$O(N\'logN )$$\n\n- Space complexity:\n $$O(1)$$\n\n# Code\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n arr[0]=1\n for i in range(1,len(arr)):\n if arr[i]-arr[i-1]>1:arr[i]=arr[i-1]+1\n return arr[-1]\n``` | 8 | There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point.
Every day, each cell infected with a virus variant will spread the virus to **all** neighboring points in the **four** cardinal directions (i.e. up, down, left, and right). If a cell has multiple variants, all the variants will spread without interfering with each other.
Given an integer `k`, return _the **minimum integer** number of days for **any** point to contain **at least**_ `k` _of the unique virus variants_.
**Example 1:**
**Input:** points = \[\[1,1\],\[6,1\]\], k = 2
**Output:** 3
**Explanation:** On day 3, points (3,1) and (4,1) will contain both virus variants. Note that these are not the only points that will contain both virus variants.
**Example 2:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 2
**Output:** 2
**Explanation:** On day 2, points (1,3), (2,3), (2,2), and (3,2) will contain the first two viruses. Note that these are not the only points that will contain both virus variants.
**Example 3:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 3
**Output:** 4
**Explanation:** On day 4, the point (5,2) will contain all 3 viruses. Note that this is not the only point that will contain all 3 virus variants.
**Constraints:**
* `n == points.length`
* `2 <= n <= 50`
* `points[i].length == 2`
* `1 <= xi, yi <= 100`
* `2 <= k <= n` | Sort the Array. Decrement each element to the largest integer that satisfies the conditions. |
Python || Beats 100% || beginner friendly | maximum-element-after-decreasing-and-rearranging | 0 | 1 | \n# Code\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n max_val = 1\n\n for i in range(1, len(arr)):\n if arr[i] > max_val:\n max_val += 1\n\n return max_val\n``` | 1 | You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions:
* The value of the **first** element in `arr` must be `1`.
* The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`.
There are 2 types of operations that you can perform any number of times:
* **Decrease** the value of any element of `arr` to a **smaller positive integer**.
* **Rearrange** the elements of `arr` to be in any order.
Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_.
**Example 1:**
**Input:** arr = \[2,2,1,2,1\]
**Output:** 2
**Explanation:**
We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`.
The largest element in `arr` is 2.
**Example 2:**
**Input:** arr = \[100,1,1000\]
**Output:** 3
**Explanation:**
One possible way to satisfy the conditions is by doing the following:
1. Rearrange `arr` so it becomes `[1,100,1000]`.
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now `arr = [1,2,3], which` satisfies the conditions.
The largest element in `arr is 3.`
**Example 3:**
**Input:** arr = \[1,2,3,4,5\]
**Output:** 5
**Explanation:** The array already satisfies the conditions, and the largest element is 5.
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= arr[i] <= 109` | null |
Python || Beats 100% || beginner friendly | maximum-element-after-decreasing-and-rearranging | 0 | 1 | \n# Code\n```\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n arr.sort()\n max_val = 1\n\n for i in range(1, len(arr)):\n if arr[i] > max_val:\n max_val += 1\n\n return max_val\n``` | 1 | There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point.
Every day, each cell infected with a virus variant will spread the virus to **all** neighboring points in the **four** cardinal directions (i.e. up, down, left, and right). If a cell has multiple variants, all the variants will spread without interfering with each other.
Given an integer `k`, return _the **minimum integer** number of days for **any** point to contain **at least**_ `k` _of the unique virus variants_.
**Example 1:**
**Input:** points = \[\[1,1\],\[6,1\]\], k = 2
**Output:** 3
**Explanation:** On day 3, points (3,1) and (4,1) will contain both virus variants. Note that these are not the only points that will contain both virus variants.
**Example 2:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 2
**Output:** 2
**Explanation:** On day 2, points (1,3), (2,3), (2,2), and (3,2) will contain the first two viruses. Note that these are not the only points that will contain both virus variants.
**Example 3:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 3
**Output:** 4
**Explanation:** On day 4, the point (5,2) will contain all 3 viruses. Note that this is not the only point that will contain all 3 virus variants.
**Constraints:**
* `n == points.length`
* `2 <= n <= 50`
* `points[i].length == 2`
* `1 <= xi, yi <= 100`
* `2 <= k <= n` | Sort the Array. Decrement each element to the largest integer that satisfies the conditions. |
Simple Solution Beats 100% Runtime | maximum-element-after-decreasing-and-rearranging | 0 | 1 | # Intuition\n\nMy first thought was to return the lesser of the length of the array and the maximum value in the array:\n\n`return (maxx if (maxx:=max(arr)) < (l:=len(arr)) else l)`\n\nHowever, this approach fails because the case where most of the elements of an array are small, and only a single or few rare elements are large in relation to n, the length of the array.\n\nMore specifically, the maximum value of the $n^{th}$ term of the array depends on maximum value of the previous element at $n-1$.\n\n# Approach\n\nWe know that the first element must be 1; therefore, the maximum value for an array of length 1 is always just 1.\n\nThen, considering a two-element array, the possible values for the second element are either 1, or 2 (technically 0 would also work but that wouldn\'t really make any sense since we\'re trying to achieve a maximum): The second element\'s maximum possible value is 2 unless both original elements have a value of 1, in which case the maximum possible value is 1, due to the rule of only decreasing the elements.\n\nThe pattern becomes clearer at three elements: the maximum value of the three elements after decreasing and rearranging depends on whether the "second max" of the first two elements was 1 or 2. If 2, then the third element will increase the result by 1 if the value of that element is greater than 2. If the "second max" was 1, that means the first two elements we looked at were both 1 - in that case, once again, the max will stay at 1 only if the third value is another 1. If it is 2 or greater, we will be able to increase our result by 1, resulting in 2.\n\nThus, after sorting the array, we can start a tally at 0 that we increase by 1 iff the next value of the array is greater than the current tally value.\n\n# Complexity\n\n## Time complexity:\nPython\'s built-in sort uses an algorithm called Timsort which is $$O(n\u2217log(n))$$ in the average and worst cases, but in the best case (if the array is already sorted or nearly sorted), it is $$O(n)$$. Then, iterating through the array to compare the tally is another $$O(n)$$ operation, so our best case runtime is $$O(n)$$ and our average and worst cases are $$O(n\u2217log(n))$$\n\n## Space complexity:\nWe sort the array in-place: $$O(1)$$\n\n# Code\n\n```python\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n\n arr.sort()\n m = 0\n for v in arr:\n if v > m:\n m += 1\n return m\n```\n | 1 | You are given an array of positive integers `arr`. Perform some operations (possibly none) on `arr` so that it satisfies these conditions:
* The value of the **first** element in `arr` must be `1`.
* The absolute difference between any 2 adjacent elements must be **less than or equal to** `1`. In other words, `abs(arr[i] - arr[i - 1]) <= 1` for each `i` where `1 <= i < arr.length` (**0-indexed**). `abs(x)` is the absolute value of `x`.
There are 2 types of operations that you can perform any number of times:
* **Decrease** the value of any element of `arr` to a **smaller positive integer**.
* **Rearrange** the elements of `arr` to be in any order.
Return _the **maximum** possible value of an element in_ `arr` _after performing the operations to satisfy the conditions_.
**Example 1:**
**Input:** arr = \[2,2,1,2,1\]
**Output:** 2
**Explanation:**
We can satisfy the conditions by rearranging `arr` so it becomes `[1,2,2,2,1]`.
The largest element in `arr` is 2.
**Example 2:**
**Input:** arr = \[100,1,1000\]
**Output:** 3
**Explanation:**
One possible way to satisfy the conditions is by doing the following:
1. Rearrange `arr` so it becomes `[1,100,1000]`.
2. Decrease the value of the second element to 2.
3. Decrease the value of the third element to 3.
Now `arr = [1,2,3], which` satisfies the conditions.
The largest element in `arr is 3.`
**Example 3:**
**Input:** arr = \[1,2,3,4,5\]
**Output:** 5
**Explanation:** The array already satisfies the conditions, and the largest element is 5.
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= arr[i] <= 109` | null |
Simple Solution Beats 100% Runtime | maximum-element-after-decreasing-and-rearranging | 0 | 1 | # Intuition\n\nMy first thought was to return the lesser of the length of the array and the maximum value in the array:\n\n`return (maxx if (maxx:=max(arr)) < (l:=len(arr)) else l)`\n\nHowever, this approach fails because the case where most of the elements of an array are small, and only a single or few rare elements are large in relation to n, the length of the array.\n\nMore specifically, the maximum value of the $n^{th}$ term of the array depends on maximum value of the previous element at $n-1$.\n\n# Approach\n\nWe know that the first element must be 1; therefore, the maximum value for an array of length 1 is always just 1.\n\nThen, considering a two-element array, the possible values for the second element are either 1, or 2 (technically 0 would also work but that wouldn\'t really make any sense since we\'re trying to achieve a maximum): The second element\'s maximum possible value is 2 unless both original elements have a value of 1, in which case the maximum possible value is 1, due to the rule of only decreasing the elements.\n\nThe pattern becomes clearer at three elements: the maximum value of the three elements after decreasing and rearranging depends on whether the "second max" of the first two elements was 1 or 2. If 2, then the third element will increase the result by 1 if the value of that element is greater than 2. If the "second max" was 1, that means the first two elements we looked at were both 1 - in that case, once again, the max will stay at 1 only if the third value is another 1. If it is 2 or greater, we will be able to increase our result by 1, resulting in 2.\n\nThus, after sorting the array, we can start a tally at 0 that we increase by 1 iff the next value of the array is greater than the current tally value.\n\n# Complexity\n\n## Time complexity:\nPython\'s built-in sort uses an algorithm called Timsort which is $$O(n\u2217log(n))$$ in the average and worst cases, but in the best case (if the array is already sorted or nearly sorted), it is $$O(n)$$. Then, iterating through the array to compare the tally is another $$O(n)$$ operation, so our best case runtime is $$O(n)$$ and our average and worst cases are $$O(n\u2217log(n))$$\n\n## Space complexity:\nWe sort the array in-place: $$O(1)$$\n\n# Code\n\n```python\nclass Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n\n arr.sort()\n m = 0\n for v in arr:\n if v > m:\n m += 1\n return m\n```\n | 1 | There are `n` **unique** virus variants in an infinite 2D grid. You are given a 2D array `points`, where `points[i] = [xi, yi]` represents a virus originating at `(xi, yi)` on day `0`. Note that it is possible for **multiple** virus variants to originate at the **same** point.
Every day, each cell infected with a virus variant will spread the virus to **all** neighboring points in the **four** cardinal directions (i.e. up, down, left, and right). If a cell has multiple variants, all the variants will spread without interfering with each other.
Given an integer `k`, return _the **minimum integer** number of days for **any** point to contain **at least**_ `k` _of the unique virus variants_.
**Example 1:**
**Input:** points = \[\[1,1\],\[6,1\]\], k = 2
**Output:** 3
**Explanation:** On day 3, points (3,1) and (4,1) will contain both virus variants. Note that these are not the only points that will contain both virus variants.
**Example 2:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 2
**Output:** 2
**Explanation:** On day 2, points (1,3), (2,3), (2,2), and (3,2) will contain the first two viruses. Note that these are not the only points that will contain both virus variants.
**Example 3:**
**Input:** points = \[\[3,3\],\[1,2\],\[9,2\]\], k = 3
**Output:** 4
**Explanation:** On day 4, the point (5,2) will contain all 3 viruses. Note that this is not the only point that will contain all 3 virus variants.
**Constraints:**
* `n == points.length`
* `2 <= n <= 50`
* `points[i].length == 2`
* `1 <= xi, yi <= 100`
* `2 <= k <= n` | Sort the Array. Decrement each element to the largest integer that satisfies the conditions. |
Best Solution Explained | closest-room | 1 | 1 | \n```\nclass Solution {\n public int[] closestRoom(int[][] rooms, int[][] queries) {\n int n = rooms.length, k = queries.length;\n Integer[] indexes = new Integer[k];\n for (int i = 0; i < k; i++) indexes[i] = i;\n Arrays.sort(rooms, (a, b) -> Integer.compare(b[1], a[1])); //Sort by decreasing order of room size\n Arrays.sort(indexes, (a, b) -> Integer.compare(queries[b][1], queries[a][1])); // Sort by decreasing order of query minSize\n TreeSet<Integer> roomIdsSoFar = new TreeSet<>();\n int[] ans = new int[k];\n int i = 0;\n for (int index : indexes) {\n while (i < n && rooms[i][1] >= queries[index][1]) { // Add id of the room which its size >= query minSize\n roomIdsSoFar.add(rooms[i++][0]);\n }\n ans[index] = searchClosetRoomId(roomIdsSoFar, queries[index][0]);\n }\n return ans;\n }\n int searchClosetRoomId(TreeSet<Integer> treeSet, int preferredId) {\n Integer floor = treeSet.floor(preferredId);\n Integer ceiling = treeSet.ceiling(preferredId);\n int ansAbs = Integer.MAX_VALUE, ans = -1;\n if (floor != null) {\n ans = floor;\n ansAbs = Math.abs(preferredId - floor);\n }\n if (ceiling != null && ansAbs > Math.abs(preferredId - ceiling)) {\n ans = ceiling;\n }\n return ans;\n }\n}\n``` | 0 | There is a hotel with `n` rooms. The rooms are represented by a 2D integer array `rooms` where `rooms[i] = [roomIdi, sizei]` denotes that there is a room with room number `roomIdi` and size equal to `sizei`. Each `roomIdi` is guaranteed to be **unique**.
You are also given `k` queries in a 2D array `queries` where `queries[j] = [preferredj, minSizej]`. The answer to the `jth` query is the room number `id` of a room such that:
* The room has a size of **at least** `minSizej`, and
* `abs(id - preferredj)` is **minimized**, where `abs(x)` is the absolute value of `x`.
If there is a **tie** in the absolute difference, then use the room with the **smallest** such `id`. If there is **no such room**, the answer is `-1`.
Return _an array_ `answer` _of length_ `k` _where_ `answer[j]` _contains the answer to the_ `jth` _query_.
**Example 1:**
**Input:** rooms = \[\[2,2\],\[1,2\],\[3,2\]\], queries = \[\[3,1\],\[3,3\],\[5,2\]\]
**Output:** \[3,-1,3\]
**Explanation:** The answers to the queries are as follows:
Query = \[3,1\]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3.
Query = \[3,3\]: There are no rooms with a size of at least 3, so the answer is -1.
Query = \[5,2\]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3.
**Example 2:**
**Input:** rooms = \[\[1,4\],\[2,3\],\[3,5\],\[4,1\],\[5,2\]\], queries = \[\[2,3\],\[2,4\],\[2,5\]\]
**Output:** \[2,1,3\]
**Explanation:** The answers to the queries are as follows:
Query = \[2,3\]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2.
Query = \[2,4\]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller.
Query = \[2,5\]: Room number 3 is the only room with a size of at least 5. The answer is 3.
**Constraints:**
* `n == rooms.length`
* `1 <= n <= 105`
* `k == queries.length`
* `1 <= k <= 104`
* `1 <= roomIdi, preferredj <= 107`
* `1 <= sizei, minSizej <= 107` | Search for the largest integer in the range [0, n - k] This integer is the first element in the subarray. You should take it with the k - 1 elements after it. |
Best Solution Explained | closest-room | 1 | 1 | \n```\nclass Solution {\n public int[] closestRoom(int[][] rooms, int[][] queries) {\n int n = rooms.length, k = queries.length;\n Integer[] indexes = new Integer[k];\n for (int i = 0; i < k; i++) indexes[i] = i;\n Arrays.sort(rooms, (a, b) -> Integer.compare(b[1], a[1])); //Sort by decreasing order of room size\n Arrays.sort(indexes, (a, b) -> Integer.compare(queries[b][1], queries[a][1])); // Sort by decreasing order of query minSize\n TreeSet<Integer> roomIdsSoFar = new TreeSet<>();\n int[] ans = new int[k];\n int i = 0;\n for (int index : indexes) {\n while (i < n && rooms[i][1] >= queries[index][1]) { // Add id of the room which its size >= query minSize\n roomIdsSoFar.add(rooms[i++][0]);\n }\n ans[index] = searchClosetRoomId(roomIdsSoFar, queries[index][0]);\n }\n return ans;\n }\n int searchClosetRoomId(TreeSet<Integer> treeSet, int preferredId) {\n Integer floor = treeSet.floor(preferredId);\n Integer ceiling = treeSet.ceiling(preferredId);\n int ansAbs = Integer.MAX_VALUE, ans = -1;\n if (floor != null) {\n ans = floor;\n ansAbs = Math.abs(preferredId - floor);\n }\n if (ceiling != null && ansAbs > Math.abs(preferredId - ceiling)) {\n ans = ceiling;\n }\n return ans;\n }\n}\n``` | 0 | A **fancy string** is a string where no **three** **consecutive** characters are equal.
Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**.
Return _the final string after the deletion_. It can be shown that the answer will always be **unique**.
**Example 1:**
**Input:** s = "leeetcode "
**Output:** "leetcode "
**Explanation:**
Remove an 'e' from the first group of 'e's to create "leetcode ".
No three consecutive characters are equal, so return "leetcode ".
**Example 2:**
**Input:** s = "aaabaaaa "
**Output:** "aabaa "
**Explanation:**
Remove an 'a' from the first group of 'a's to create "aabaaaa ".
Remove two 'a's from the second group of 'a's to create "aabaa ".
No three consecutive characters are equal, so return "aabaa ".
**Example 3:**
**Input:** s = "aab "
**Output:** "aab "
**Explanation:** No three consecutive characters are equal, so return "aab ".
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists only of lowercase English letters. | Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time. |
Straightforward | minimum-distance-to-the-target-element | 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 getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n l=[]\n for i in range(len(nums)):\n if nums[i]==target:\n l.append(abs(i-start))\n return min(l)\n``` | 2 | Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`.
Return `abs(i - start)`.
It is **guaranteed** that `target` exists in `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\], target = 5, start = 3
**Output:** 1
**Explanation:** nums\[4\] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.
**Example 2:**
**Input:** nums = \[1\], target = 1, start = 0
**Output:** 0
**Explanation:** nums\[0\] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.
**Example 3:**
**Input:** nums = \[1,1,1,1,1,1,1,1,1,1\], target = 1, start = 0
**Output:** 0
**Explanation:** Every value of nums is 1, but nums\[0\] minimizes abs(i - start), which is abs(0 - 0) = 0.
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* `0 <= start < nums.length`
* `target` is in `nums`. | Use a dictionary to count the frequency of each number. |
Straightforward | minimum-distance-to-the-target-element | 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 getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n l=[]\n for i in range(len(nums)):\n if nums[i]==target:\n l.append(abs(i-start))\n return min(l)\n``` | 2 | You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105` | Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start). |
Python easy solution . | minimum-distance-to-the-target-element | 0 | 1 | \n# Code\n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n x = []\n for i in range(len(nums)):\n if nums[i] == target:\n x.append(abs(i- start))\n return min(x)\n``` | 1 | Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`.
Return `abs(i - start)`.
It is **guaranteed** that `target` exists in `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\], target = 5, start = 3
**Output:** 1
**Explanation:** nums\[4\] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.
**Example 2:**
**Input:** nums = \[1\], target = 1, start = 0
**Output:** 0
**Explanation:** nums\[0\] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.
**Example 3:**
**Input:** nums = \[1,1,1,1,1,1,1,1,1,1\], target = 1, start = 0
**Output:** 0
**Explanation:** Every value of nums is 1, but nums\[0\] minimizes abs(i - start), which is abs(0 - 0) = 0.
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* `0 <= start < nums.length`
* `target` is in `nums`. | Use a dictionary to count the frequency of each number. |
Python easy solution . | minimum-distance-to-the-target-element | 0 | 1 | \n# Code\n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n x = []\n for i in range(len(nums)):\n if nums[i] == target:\n x.append(abs(i- start))\n return min(x)\n``` | 1 | You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105` | Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start). |
minimum-distance-to-the-target-element | minimum-distance-to-the-target-element | 0 | 1 | # Code\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} target\n * @param {number} start\n * @return {number}\n */\nvar getMinDistance = function(nums, t, s) {\n let o = Number.POSITIVE_INFINITY;\n for(let i = 0; i<nums.length;i++){\n if(nums[i]==t){\n o = Math.min(o,Math.abs(s - i));\n }\n }\n return o\n \n};\n```\n\n```python []\nclass Solution:\n def getMinDistance(self, nums: List[int], o: int, start: int) -> int:\n t = float("inf")\n for i in range(len(nums)):\n if nums[i]==o:\n t = min(t,abs(start - i))\n return t\n```\n | 1 | Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`.
Return `abs(i - start)`.
It is **guaranteed** that `target` exists in `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\], target = 5, start = 3
**Output:** 1
**Explanation:** nums\[4\] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.
**Example 2:**
**Input:** nums = \[1\], target = 1, start = 0
**Output:** 0
**Explanation:** nums\[0\] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.
**Example 3:**
**Input:** nums = \[1,1,1,1,1,1,1,1,1,1\], target = 1, start = 0
**Output:** 0
**Explanation:** Every value of nums is 1, but nums\[0\] minimizes abs(i - start), which is abs(0 - 0) = 0.
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* `0 <= start < nums.length`
* `target` is in `nums`. | Use a dictionary to count the frequency of each number. |
minimum-distance-to-the-target-element | minimum-distance-to-the-target-element | 0 | 1 | # Code\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} target\n * @param {number} start\n * @return {number}\n */\nvar getMinDistance = function(nums, t, s) {\n let o = Number.POSITIVE_INFINITY;\n for(let i = 0; i<nums.length;i++){\n if(nums[i]==t){\n o = Math.min(o,Math.abs(s - i));\n }\n }\n return o\n \n};\n```\n\n```python []\nclass Solution:\n def getMinDistance(self, nums: List[int], o: int, start: int) -> int:\n t = float("inf")\n for i in range(len(nums)):\n if nums[i]==o:\n t = min(t,abs(start - i))\n return t\n```\n | 1 | You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105` | Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start). |
Python Easy Solution | minimum-distance-to-the-target-element | 0 | 1 | # Code\n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n curVal=len(nums)\n for i in range(start,len(nums)):\n if nums[i]==target:\n curVal=min(curVal,abs(i-start))\n break\n j=start\n while(j>=0):\n if nums[j]==target:\n curVal=min(curVal,abs(j-start))\n break\n j-=1\n return curVal\n \n \n``` | 1 | Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`.
Return `abs(i - start)`.
It is **guaranteed** that `target` exists in `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\], target = 5, start = 3
**Output:** 1
**Explanation:** nums\[4\] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.
**Example 2:**
**Input:** nums = \[1\], target = 1, start = 0
**Output:** 0
**Explanation:** nums\[0\] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.
**Example 3:**
**Input:** nums = \[1,1,1,1,1,1,1,1,1,1\], target = 1, start = 0
**Output:** 0
**Explanation:** Every value of nums is 1, but nums\[0\] minimizes abs(i - start), which is abs(0 - 0) = 0.
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* `0 <= start < nums.length`
* `target` is in `nums`. | Use a dictionary to count the frequency of each number. |
Python Easy Solution | minimum-distance-to-the-target-element | 0 | 1 | # Code\n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n curVal=len(nums)\n for i in range(start,len(nums)):\n if nums[i]==target:\n curVal=min(curVal,abs(i-start))\n break\n j=start\n while(j>=0):\n if nums[j]==target:\n curVal=min(curVal,abs(j-start))\n break\n j-=1\n return curVal\n \n \n``` | 1 | You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105` | Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start). |
[Python3] linear sweep | minimum-distance-to-the-target-element | 0 | 1 | \n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n ans = inf\n for i, x in enumerate(nums): \n if x == target: \n ans = min(ans, abs(i - start))\n return ans \n``` | 13 | Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`.
Return `abs(i - start)`.
It is **guaranteed** that `target` exists in `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\], target = 5, start = 3
**Output:** 1
**Explanation:** nums\[4\] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.
**Example 2:**
**Input:** nums = \[1\], target = 1, start = 0
**Output:** 0
**Explanation:** nums\[0\] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.
**Example 3:**
**Input:** nums = \[1,1,1,1,1,1,1,1,1,1\], target = 1, start = 0
**Output:** 0
**Explanation:** Every value of nums is 1, but nums\[0\] minimizes abs(i - start), which is abs(0 - 0) = 0.
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* `0 <= start < nums.length`
* `target` is in `nums`. | Use a dictionary to count the frequency of each number. |
[Python3] linear sweep | minimum-distance-to-the-target-element | 0 | 1 | \n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n ans = inf\n for i, x in enumerate(nums): \n if x == target: \n ans = min(ans, abs(i - start))\n return ans \n``` | 13 | You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105` | Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start). |
1-liner py3 | minimum-distance-to-the-target-element | 0 | 1 | # Code\n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n return min(abs(i - start) for i, v in enumerate(nums) if v == target)\n``` | 0 | Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`.
Return `abs(i - start)`.
It is **guaranteed** that `target` exists in `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\], target = 5, start = 3
**Output:** 1
**Explanation:** nums\[4\] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.
**Example 2:**
**Input:** nums = \[1\], target = 1, start = 0
**Output:** 0
**Explanation:** nums\[0\] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.
**Example 3:**
**Input:** nums = \[1,1,1,1,1,1,1,1,1,1\], target = 1, start = 0
**Output:** 0
**Explanation:** Every value of nums is 1, but nums\[0\] minimizes abs(i - start), which is abs(0 - 0) = 0.
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* `0 <= start < nums.length`
* `target` is in `nums`. | Use a dictionary to count the frequency of each number. |
1-liner py3 | minimum-distance-to-the-target-element | 0 | 1 | # Code\n```\nclass Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n return min(abs(i - start) for i, v in enumerate(nums) if v == target)\n``` | 0 | You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105` | Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start). |
Easy Solution | minimum-distance-to-the-target-element | 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 getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n \n indices = [x for x in range(len(nums))]\n dictionary = dict(zip(indices, nums))\n answer = [key for key, value in dictionary.items() if value==target]\n result = [abs(x-start) for x in answer]\n return min(result)\n \n``` | 0 | Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`.
Return `abs(i - start)`.
It is **guaranteed** that `target` exists in `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\], target = 5, start = 3
**Output:** 1
**Explanation:** nums\[4\] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.
**Example 2:**
**Input:** nums = \[1\], target = 1, start = 0
**Output:** 0
**Explanation:** nums\[0\] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.
**Example 3:**
**Input:** nums = \[1,1,1,1,1,1,1,1,1,1\], target = 1, start = 0
**Output:** 0
**Explanation:** Every value of nums is 1, but nums\[0\] minimizes abs(i - start), which is abs(0 - 0) = 0.
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 104`
* `0 <= start < nums.length`
* `target` is in `nums`. | Use a dictionary to count the frequency of each number. |
Easy Solution | minimum-distance-to-the-target-element | 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 getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n \n indices = [x for x in range(len(nums))]\n dictionary = dict(zip(indices, nums))\n answer = [key for key, value in dictionary.items() if value==target]\n result = [abs(x-start) for x in answer]\n return min(result)\n \n``` | 0 | You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times:
* Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`.
Two elements are considered **adjacent** if and only if they share a **border**.
Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._
**Example 1:**
**Input:** matrix = \[\[1,-1\],\[-1,1\]\]
**Output:** 4
**Explanation:** We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
**Example 2:**
**Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\]
**Output:** 16
**Explanation:** We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `2 <= n <= 250`
* `-105 <= matrix[i][j] <= 105` | Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.