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 |
|---|---|---|---|---|---|---|---|
[We💕Simple] One Liner! (Regex) - Shorter than thought | largest-3-same-digit-number-in-string | 0 | 1 | I like solving problems in a simple way. Regex is one of the very good methods for solving problems simply. If you are curious about other solutions using Regex, please check my other solutions too.\n\n\n```Python []\nclass Solution:\n def largestGoodInteger(self, num: str) -> str:\n return max(re.findall(r\'... | 2 | You are given a string `num` representing a large integer. An integer is **good** if it meets the following conditions:
* It is a **substring** of `num` with length `3`.
* It consists of only one unique digit.
Return _the **maximum good** integer as a **string** or an empty string_ `" "` _if no such integer exist... | Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place. |
Sliding Window with fixed window size in Python | largest-3-same-digit-number-in-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Sliding Window with fixed window size\n- In this problem, the window size is 3\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Compare the current character with the previous character\n - If they are the same... | 2 | You are given a string `num` representing a large integer. An integer is **good** if it meets the following conditions:
* It is a **substring** of `num` with length `3`.
* It consists of only one unique digit.
Return _the **maximum good** integer as a **string** or an empty string_ `" "` _if no such integer exist... | Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place. |
🚀✅🚀 Easy solution for Beginner Friendly [Python / C# / Java / Rust] 🔥🔥 | largest-3-same-digit-number-in-string | 1 | 1 | # Intuition\nThe goal of the code appears to be finding the largest three-digit substring in the given number `num` where all three digits are the same.\n\n# Approach\nThe approach taken in the code is to iterate through the given number `num` and check for consecutive three-digit substrings where all three digits are ... | 13 | You are given a string `num` representing a large integer. An integer is **good** if it meets the following conditions:
* It is a **substring** of `num` with length `3`.
* It consists of only one unique digit.
Return _the **maximum good** integer as a **string** or an empty string_ `" "` _if no such integer exist... | Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place. |
Easy Python Solution with basic Knowledge | largest-3-same-digit-number-in-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSolve Problem Easily\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 ... | 1 | You are given a string `num` representing a large integer. An integer is **good** if it meets the following conditions:
* It is a **substring** of `num` with length `3`.
* It consists of only one unique digit.
Return _the **maximum good** integer as a **string** or an empty string_ `" "` _if no such integer exist... | Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place. |
Python Easiest Solution | 93% Faster | largest-3-same-digit-number-in-string | 0 | 1 | # Approach\n- Initialize two variable count (int) and l(list)\n- Initialize value of a counter at 1. If a streak of 3 is found, append it to the list (l)\n- If the list (l) is empty, return an empty string. \n- Otherwise, find the maximum in the list (l) and return it in form of string three times.\n\n# Complexity\n- T... | 1 | You are given a string `num` representing a large integer. An integer is **good** if it meets the following conditions:
* It is a **substring** of `num` with length `3`.
* It consists of only one unique digit.
Return _the **maximum good** integer as a **string** or an empty string_ `" "` _if no such integer exist... | Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place. |
100% runtime | largest-3-same-digit-number-in-string | 0 | 1 | # Code\n```\nclass Solution:\n def largestGoodInteger(self, num: str) -> str:\n strike = 1\n biggest = -1\n for i in range(0, len(num) - 1):\n if num[i] == num[i + 1]:\n strike += 1\n if strike == 3:\n newStrike = int(num[i])\n ... | 1 | You are given a string `num` representing a large integer. An integer is **good** if it meets the following conditions:
* It is a **substring** of `num` with length `3`.
* It consists of only one unique digit.
Return _the **maximum good** integer as a **string** or an empty string_ `" "` _if no such integer exist... | Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place. |
Largest 3-Same-Digit Number in String | largest-3-same-digit-number-in-string | 0 | 1 | \n\n# Approach\nIterate through the string to find a substring(largest) of length 3 that has same digit.\n\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def largestGoodInteger(self, num: str) -> str:\n mgi = ""\n for i in range(len(num) - 2):\n ... | 1 | You are given a string `num` representing a large integer. An integer is **good** if it meets the following conditions:
* It is a **substring** of `num` with length `3`.
* It consists of only one unique digit.
Return _the **maximum good** integer as a **string** or an empty string_ `" "` _if no such integer exist... | Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place. |
[Python3/Java/C++/Go/TypeScript] Enumeration | largest-3-same-digit-number-in-string | 1 | 1 | **Solution 1: Enumeration**\n\nWe can enumerate each digit $i$ from large to small, where $0 \\le i \\le 9$, and then check whether the string $s$ consisting of three consecutive $i$ is a substring of $num$. If it is, we directly return $s$.\n\nIf we have enumerated all the possible values of $i$ and still haven\'t fou... | 1 | You are given a string `num` representing a large integer. An integer is **good** if it meets the following conditions:
* It is a **substring** of `num` with length `3`.
* It consists of only one unique digit.
Return _the **maximum good** integer as a **string** or an empty string_ `" "` _if no such integer exist... | Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place. |
Vey Easy Solution using Python|| BruthForce solution⚡❤️ | largest-3-same-digit-number-in-string | 0 | 1 | \n# Code\n```\nclass Solution:\n def largestGoodInteger(self, num: str) -> str:\n ans=-1\n for i in range(2,len(num)):\n if (num[i]==num[i-1]==num[i-2]):\n ans=max(ans,int(num[i]))\n \n if ans==-1:\n return ""\n else:\n return 3*str(a... | 1 | You are given a string `num` representing a large integer. An integer is **good** if it meets the following conditions:
* It is a **substring** of `num` with length `3`.
* It consists of only one unique digit.
Return _the **maximum good** integer as a **string** or an empty string_ `" "` _if no such integer exist... | Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place. |
✅ 89.45% Post-order traversal | count-nodes-equal-to-average-of-subtree | 1 | 1 | # Intuition\nThe problem asks us to count the number of nodes where the node\'s value is equal to the average of its subtree (including itself). To calculate the average, we need the sum and count of nodes in the subtree. Our first thought could be to traverse the tree and, for every node, calculate the sum and count o... | 68 | Given the `root` of a binary tree, return _the number of nodes where the value of the node is equal to the **average** of the values in its **subtree**_.
**Note:**
* The **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer.
* A **subtree** of `r... | Could you put the elements smaller than the pivot and greater than the pivot in a separate list as in the sequence that they occur? With the separate lists generated, could you then generate the result? |
【Video】Give me 8 minutes - How we think about a solution - Why we use postorder traversal? | count-nodes-equal-to-average-of-subtree | 1 | 1 | # Intuition\nCalculate subtree of left and right child frist\n\n---\n\n# Solution Video\n\nhttps://youtu.be/MV6NpUXCfUU\n\n\u25A0 Timeline of the video\n`0:05` Which traversal do you use for this question?\n`1:55` How do you calculate information you need?\n`3:34` How to write Inorder, Preorder, Postorder\n`4:16` Codin... | 44 | Given the `root` of a binary tree, return _the number of nodes where the value of the node is equal to the **average** of the values in its **subtree**_.
**Note:**
* The **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer.
* A **subtree** of `r... | Could you put the elements smaller than the pivot and greater than the pivot in a separate list as in the sequence that they occur? With the separate lists generated, could you then generate the result? |
🚀 Beats 100% | Easy To Understand 🚀🔥 | count-nodes-equal-to-average-of-subtree | 1 | 1 | # Intuition\n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time com... | 3 | Given the `root` of a binary tree, return _the number of nodes where the value of the node is equal to the **average** of the values in its **subtree**_.
**Note:**
* The **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer.
* A **subtree** of `r... | Could you put the elements smaller than the pivot and greater than the pivot in a separate list as in the sequence that they occur? With the separate lists generated, could you then generate the result? |
Detailed Dry Run of DFS on Trees!! 😸 | count-nodes-equal-to-average-of-subtree | 0 | 1 | # Intuition\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nDFS \n\n# Complexity\n- Time complexity:\n<!... | 2 | Given the `root` of a binary tree, return _the number of nodes where the value of the node is equal to the **average** of the values in its **subtree**_.
**Note:**
* The **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer.
* A **subtree** of `r... | Could you put the elements smaller than the pivot and greater than the pivot in a separate list as in the sequence that they occur? With the separate lists generated, could you then generate the result? |
g gun post-order traversal DFS solution for real men in python | count-nodes-equal-to-average-of-subtree | 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)$$ --... | 1 | Given the `root` of a binary tree, return _the number of nodes where the value of the node is equal to the **average** of the values in its **subtree**_.
**Note:**
* The **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer.
* A **subtree** of `r... | Could you put the elements smaller than the pivot and greater than the pivot in a separate list as in the sequence that they occur? With the separate lists generated, could you then generate the result? |
🚀 100% || DFS || Explained Intuition🚀 | count-nodes-equal-to-average-of-subtree | 1 | 1 | # Problem Description\n\nGiven the **root** of a binary tree. The task is to determine the **number** of nodes in the tree whose value **matches** the floored **average** of all the values within their respective **subtrees**. In other words, you need to count the nodes where the node\'s value is equal to the integer a... | 68 | Given the `root` of a binary tree, return _the number of nodes where the value of the node is equal to the **average** of the values in its **subtree**_.
**Note:**
* The **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer.
* A **subtree** of `r... | Could you put the elements smaller than the pivot and greater than the pivot in a separate list as in the sequence that they occur? With the separate lists generated, could you then generate the result? |
Beats 98% DFS Very Intuitive method | count-nodes-equal-to-average-of-subtree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEvery node requires the sum of its subtree and length, so as we work our way up the tree from the bottom, we return the sum as well as the length and sum of the left and right branches. We then add this to the node and determine whether t... | 1 | Given the `root` of a binary tree, return _the number of nodes where the value of the node is equal to the **average** of the values in its **subtree**_.
**Note:**
* The **average** of `n` elements is the **sum** of the `n` elements divided by `n` and **rounded down** to the nearest integer.
* A **subtree** of `r... | Could you put the elements smaller than the pivot and greater than the pivot in a separate list as in the sequence that they occur? With the separate lists generated, could you then generate the result? |
[Python3] group-by-group | count-number-of-texts | 0 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/9aa0edb0815f3e0a75a47808e1690ca424f169e5) for solutions of weekly 292. \n\n```\nclass Solution:\n def countTexts(self, pressedKeys: str) -> int:\n MOD = 1_000_000_007 \n \n @cache \n def fn(n, k): \n """Ret... | 9 | Alice is texting Bob using her phone. The **mapping** of digits to letters is shown in the figure below.
In order to **add** a letter, Alice has to **press** the key of the corresponding digit `i` times, where `i` is the position of the letter in the key.
* For example, to add the letter `'s'`, Alice has to press `... | Define a separate function Cost(mm, ss) where 0 <= mm <= 99 and 0 <= ss <= 99. This function should calculate the cost of setting the cocking time to mm minutes and ss seconds The range of the minutes is small (i.e., [0, 99]), how can you use that? For every mm in [0, 99], calculate the needed ss to make mm:ss equal to... |
✅ Python Simple Memoisation/Caching | check-if-there-is-a-valid-parentheses-string-path | 0 | 1 | There are two main parts of the solution:\n1. Logic to determine whether a sequence is [Balanced Paranteses](https://leetcode.com/problems/valid-parentheses/). This can be achieved using `Stack`(`O(N) space`) or using a `counter` variable(`O(1) space`). I will be using the latter.\n2. A recursive function to check the ... | 15 | A parentheses string is a **non-empty** string consisting only of `'('` and `')'`. It is **valid** if **any** of the following conditions is **true**:
* It is `()`.
* It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are valid parentheses strings.
* It can be written as `(A)`, where `A` is... | The lowest possible difference can be obtained when the sum of the first n elements in the resultant array is minimum, and the sum of the next n elements is maximum. For every index i, think about how you can find the minimum possible sum of n elements with indices lesser or equal to i, if possible. Similarly, for ever... |
100% Faster Code | C++ and Python | Sliding Window | String Handling | find-the-k-beauty-of-a-number | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSliding Window\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity... | 1 | The **k-beauty** of an integer `num` is defined as the number of **substrings** of `num` when it is read as a string that meet the following conditions:
* It has a length of `k`.
* It is a divisor of `num`.
Given integers `num` and `k`, return _the k-beauty of_ `num`.
Note:
* **Leading zeros** are allowed.
* ... | All the elements in the array should be counted except for the minimum and maximum elements. If the array has n elements, the answer will be n - count(min(nums)) - count(max(nums)) This formula will not work in case the array has all the elements equal, why? |
Simple Sliding Window implementation in O(n) | find-the-k-beauty-of-a-number | 0 | 1 | # Approach\n###### Fixed Sized Sliding Window\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def divisorSubstrings(self, num: int, k: int) -> int:\n \n sub_arr = str(num)[:k]\n count = 0\n\n if(num % int(sub_arr) == 0):\n ... | 1 | The **k-beauty** of an integer `num` is defined as the number of **substrings** of `num` when it is read as a string that meet the following conditions:
* It has a length of `k`.
* It is a divisor of `num`.
Given integers `num` and `k`, return _the k-beauty of_ `num`.
Note:
* **Leading zeros** are allowed.
* ... | All the elements in the array should be counted except for the minimum and maximum elements. If the array has n elements, the answer will be n - count(min(nums)) - count(max(nums)) This formula will not work in case the array has all the elements equal, why? |
Easy Solution Python3 | find-the-k-beauty-of-a-number | 0 | 1 | ```\nclass Solution:\n def divisorSubstrings(self, num: int, k: int) -> int:\n \n ans = 0;\n for x in range(len(str(num))):\n substr = str(num)[x:x+k:];\n \n if len(substr) < k: break;\n elif int(substr) == 0: continue;\n\n ans += num % int(... | 0 | The **k-beauty** of an integer `num` is defined as the number of **substrings** of `num` when it is read as a string that meet the following conditions:
* It has a length of `k`.
* It is a divisor of `num`.
Given integers `num` and `k`, return _the k-beauty of_ `num`.
Note:
* **Leading zeros** are allowed.
* ... | All the elements in the array should be counted except for the minimum and maximum elements. If the array has n elements, the answer will be n - count(min(nums)) - count(max(nums)) This formula will not work in case the array has all the elements equal, why? |
Python Elegant & Short | Sliding window | O(log10(n)) time | O(1) memory | find-the-k-beauty-of-a-number | 0 | 1 | ```\nclass Solution:\n """\n Time: O(log10(n)*k)\n Memory: O(log10(n))\n """\n\n def divisorSubstrings(self, num: int, k: int) -> int:\n str_num = str(num)\n return sum(\n num % int(str_num[i - k:i]) == 0\n for i in range(k, len(str_num) + 1)\n if int(str_... | 5 | The **k-beauty** of an integer `num` is defined as the number of **substrings** of `num` when it is read as a string that meet the following conditions:
* It has a length of `k`.
* It is a divisor of `num`.
Given integers `num` and `k`, return _the k-beauty of_ `num`.
Note:
* **Leading zeros** are allowed.
* ... | All the elements in the array should be counted except for the minimum and maximum elements. If the array has n elements, the answer will be n - count(min(nums)) - count(max(nums)) This formula will not work in case the array has all the elements equal, why? |
Prefix Sum | number-of-ways-to-split-array | 0 | 1 | **Python 3**\n```python\nclass Solution:\n def waysToSplitArray(self, n: List[int]) -> int:\n n = list(accumulate(n))\n return sum(n[i] >= n[-1] - n[i] for i in range(len(n) - 1))\n```\n\n**C++**\nWe could use a prefix sum, but in C++ we would need to store it in another `long long` vector (because of ... | 16 | You are given a **0-indexed** integer array `nums` of length `n`.
`nums` contains a **valid split** at index `i` if the following are true:
* The sum of the first `i + 1` elements is **greater than or equal to** the sum of the last `n - i - 1` elements.
* There is **at least one** element to the right of `i`. Tha... | For a given element x, how can you quickly check if x - 1 and x + 1 are present in the array without reiterating through the entire array? Use a set or a hash map. |
7 Lines Python Code || Beats 82 % | number-of-ways-to-split-array | 0 | 1 | # Intuition\nso you have to count the number of ways we can split array basically in two parts such that `sum of left Part >= right Part`\nso first find the total sum of the array\nand loop through your given array and add each element to left Part and subtract it from your totalSum (which is now your right Part)\nif ... | 2 | You are given a **0-indexed** integer array `nums` of length `n`.
`nums` contains a **valid split** at index `i` if the following are true:
* The sum of the first `i + 1` elements is **greater than or equal to** the sum of the last `n - i - 1` elements.
* There is **at least one** element to the right of `i`. Tha... | For a given element x, how can you quickly check if x - 1 and x + 1 are present in the array without reiterating through the entire array? Use a set or a hash map. |
[C++/Python3] Very Concise Prefix Sum O(1) | number-of-ways-to-split-array | 0 | 1 | **Python**\n```\nclass Solution:\n def waysToSplitArray(self, nums: List[int]) -> int:\n lsum, rsum, ans = 0, sum(nums), 0\n for i in range(len(nums) - 1):\n lsum += nums[i]\n rsum -= nums[i]\n ans += (lsum >= rsum)\n return ans\n\t\t\n```\n\n**C++**\n```\nclass ... | 4 | You are given a **0-indexed** integer array `nums` of length `n`.
`nums` contains a **valid split** at index `i` if the following are true:
* The sum of the first `i + 1` elements is **greater than or equal to** the sum of the last `n - i - 1` elements.
* There is **at least one** element to the right of `i`. Tha... | For a given element x, how can you quickly check if x - 1 and x + 1 are present in the array without reiterating through the entire array? Use a set or a hash map. |
Python3 || beats 99% || simple solution | number-of-ways-to-split-array | 0 | 1 | ```\nclass Solution:\n\tdef waysToSplitArray(self, nums: List[int]) -> int:\n s0 = sum(nums)\n s1, d = 0, 0\n for i in nums[:-1]:\n s1 += i\n if s1 >= (s0-s1):\n d += 1\n return d\n``` | 4 | You are given a **0-indexed** integer array `nums` of length `n`.
`nums` contains a **valid split** at index `i` if the following are true:
* The sum of the first `i + 1` elements is **greater than or equal to** the sum of the last `n - i - 1` elements.
* There is **at least one** element to the right of `i`. Tha... | For a given element x, how can you quickly check if x - 1 and x + 1 are present in the array without reiterating through the entire array? Use a set or a hash map. |
Simple O(n) Time and O(1) Space Solution || Python | number-of-ways-to-split-array | 0 | 1 | If you have any ***doubts*** or ***suggestion***, put in comments.\n```\nclass Solution(object):\n def waysToSplitArray(self, nums):\n lSum, rSum = 0, sum(nums)\n ans = 0\n for i in range(len(nums) - 1):\n lSum += nums[i]\n rSum -= nums[i]\n if lSum >= rSum: ans ... | 4 | You are given a **0-indexed** integer array `nums` of length `n`.
`nums` contains a **valid split** at index `i` if the following are true:
* The sum of the first `i + 1` elements is **greater than or equal to** the sum of the last `n - i - 1` elements.
* There is **at least one** element to the right of `i`. Tha... | For a given element x, how can you quickly check if x - 1 and x + 1 are present in the array without reiterating through the entire array? Use a set or a hash map. |
Python Easy Solution || Sliding Window | number-of-ways-to-split-array | 0 | 1 | # Code\n```\nclass Solution:\n def waysToSplitArray(self, nums: List[int]) -> int:\n cnt=0\n left=nums[0]\n right=sum(nums[1:])\n if left>=right:\n cnt+=1\n for i in range(1,len(nums)-1):\n left+=nums[i]\n right-=nums[i]\n if left>=right:... | 1 | You are given a **0-indexed** integer array `nums` of length `n`.
`nums` contains a **valid split** at index `i` if the following are true:
* The sum of the first `i + 1` elements is **greater than or equal to** the sum of the last `n - i - 1` elements.
* There is **at least one** element to the right of `i`. Tha... | For a given element x, how can you quickly check if x - 1 and x + 1 are present in the array without reiterating through the entire array? Use a set or a hash map. |
✅ [Python] ITS JUST PREFIX SUM !!! | number-of-ways-to-split-array | 0 | 1 | ```\nclass Solution:\n def waysToSplitArray(self, nums: List[int]) -> int:\n \n array = list(accumulate(nums, operator.add))\n count=0\n end = array[-1]\n for i in range (len(array)-1):\n \n left = array[i]-0\n right = end - array[i]\n \n... | 1 | You are given a **0-indexed** integer array `nums` of length `n`.
`nums` contains a **valid split** at index `i` if the following are true:
* The sum of the first `i + 1` elements is **greater than or equal to** the sum of the last `n - i - 1` elements.
* There is **at least one** element to the right of `i`. Tha... | For a given element x, how can you quickly check if x - 1 and x + 1 are present in the array without reiterating through the entire array? Use a set or a hash map. |
Fastest Python 3, Cumulative sum | number-of-ways-to-split-array | 0 | 1 | # Intuition\nCalculate half of array sum and compare cumalative sum\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... | 0 | You are given a **0-indexed** integer array `nums` of length `n`.
`nums` contains a **valid split** at index `i` if the following are true:
* The sum of the first `i + 1` elements is **greater than or equal to** the sum of the last `n - i - 1` elements.
* There is **at least one** element to the right of `i`. Tha... | For a given element x, how can you quickly check if x - 1 and x + 1 are present in the array without reiterating through the entire array? Use a set or a hash map. |
Beat 90% Runtime, friendly for begineers! | number-of-ways-to-split-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis code is very friendly for begineers. I\'ve introduced more local variables to make the code more reable.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe most efficient way to solve this problem is using pref... | 0 | You are given a **0-indexed** integer array `nums` of length `n`.
`nums` contains a **valid split** at index `i` if the following are true:
* The sum of the first `i + 1` elements is **greater than or equal to** the sum of the last `n - i - 1` elements.
* There is **at least one** element to the right of `i`. Tha... | For a given element x, how can you quickly check if x - 1 and x + 1 are present in the array without reiterating through the entire array? Use a set or a hash map. |
Easy short Python with explanation and example | maximum-white-tiles-covered-by-a-carpet | 0 | 1 | Brute force solution: For the start each tile, continue to iterate to the right until we run out of `carpetLen`. This runs in `O(n^2)`\n=> Better solution with runtime `O(nlogn)`:\n- We create a prefix sum array `dp` to store the TOTAL coverage from 0 to the start of each tile\n- For each tile with start `s`, we binary... | 12 | You are given a 2D integer array `tiles` where `tiles[i] = [li, ri]` represents that every tile `j` in the range `li <= j <= ri` is colored white.
You are also given an integer `carpetLen`, the length of a single carpet that can be placed **anywhere**.
Return _the **maximum** number of white tiles that can be covered... | Divide the array into two parts- one comprising of only positive integers and the other of negative integers. Merge the two parts to get the resultant array. |
[Python3] greedy | maximum-white-tiles-covered-by-a-carpet | 0 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/e134859baf16ddb9bd1645d01619449f3d067c14) for solutions of biweekly 78. \n\n```\nclass Solution:\n def maximumWhiteTiles(self, tiles: List[List[int]], carpetLen: int) -> int:\n tiles.sort()\n ans = ii = val = 0 \n for i in r... | 1 | You are given a 2D integer array `tiles` where `tiles[i] = [li, ri]` represents that every tile `j` in the range `li <= j <= ri` is colored white.
You are also given an integer `carpetLen`, the length of a single carpet that can be placed **anywhere**.
Return _the **maximum** number of white tiles that can be covered... | Divide the array into two parts- one comprising of only positive integers and the other of negative integers. Merge the two parts to get the resultant array. |
Python | Binary Search | maximum-white-tiles-covered-by-a-carpet | 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)$$ --... | 0 | You are given a 2D integer array `tiles` where `tiles[i] = [li, ri]` represents that every tile `j` in the range `li <= j <= ri` is colored white.
You are also given an integer `carpetLen`, the length of a single carpet that can be placed **anywhere**.
Return _the **maximum** number of white tiles that can be covered... | Divide the array into two parts- one comprising of only positive integers and the other of negative integers. Merge the two parts to get the resultant array. |
Same as 200 other Solutions 🙏🙏 | substring-with-largest-variance | 0 | 1 | # Code\n```\nclass Solution:\n def largestVariance(self, s: str) -> int:\n res=0\n for ch1 in set(s):\n for ch2 in set(s):\n if ch1==ch2: continue\n ch2_front=False; has_ch2=False; var=0\n for i in range(len(s)):\n if s[i]==ch1:... | 4 | The **variance** of a string is defined as the largest difference between the number of occurrences of **any** `2` characters present in the string. Note the two characters may or may not be the same.
Given a string `s` consisting of lowercase English letters only, return _the **largest variance** possible among all *... | You should test every possible assignment of good and bad people, using a bitmask. In each bitmask, if the person i is good, then his statements should be consistent with the bitmask in order for the assignment to be valid. If the assignment is valid, count how many people are good and keep track of the maximum. |
Python3 Solution | substring-with-largest-variance | 0 | 1 | \n```\nclass Solution:\n def largestVariance(self, s: str) -> int:\n chars = {}\n for c in s:\n chars[c] = chars.get(c, 0) + 1\n\n permutations = itertools.permutations(chars, 2)\n count = 0\n for a, b in permutations:\n count = max(self.kadene(a, b, s, chars)... | 2 | The **variance** of a string is defined as the largest difference between the number of occurrences of **any** `2` characters present in the string. Note the two characters may or may not be the same.
Given a string `s` consisting of lowercase English letters only, return _the **largest variance** possible among all *... | You should test every possible assignment of good and bad people, using a bitmask. In each bitmask, if the person i is good, then his statements should be consistent with the bitmask in order for the assignment to be valid. If the assignment is valid, count how many people are good and keep track of the maximum. |
Modified Kadane's with Greedy Optimization | Commented and Explained | substring-with-largest-variance | 0 | 1 | # Intuition\nThe following intuition lays out the process generally. If you want to attempt it on your own, or are doing this for class as extra credit, you should read ONLY the Intuition. It should be enough to cover your problem.\n\nRemember, extra credit is on the honor system somewhat, as I\'m judging your code aga... | 1 | The **variance** of a string is defined as the largest difference between the number of occurrences of **any** `2` characters present in the string. Note the two characters may or may not be the same.
Given a string `s` consisting of lowercase English letters only, return _the **largest variance** possible among all *... | You should test every possible assignment of good and bad people, using a bitmask. In each bitmask, if the person i is good, then his statements should be consistent with the bitmask in order for the assignment to be valid. If the assignment is valid, count how many people are good and keep track of the maximum. |
Python Solution (Beats 99%) | substring-with-largest-variance | 0 | 1 | # Intuition\nThe main idea in this problem seems to be something a little bit like best subarray sums, except instead of having a singular array to explore, you must explore one with every combination of characters in the string.\n\n# Approach\nThe idea is to test every combination of characters $a,b \\in s$ with $a \\... | 1 | The **variance** of a string is defined as the largest difference between the number of occurrences of **any** `2` characters present in the string. Note the two characters may or may not be the same.
Given a string `s` consisting of lowercase English letters only, return _the **largest variance** possible among all *... | You should test every possible assignment of good and bad people, using a bitmask. In each bitmask, if the person i is good, then his statements should be consistent with the bitmask in order for the assignment to be valid. If the assignment is valid, count how many people are good and keep track of the maximum. |
Explained Brute force with Sliding Window for beginners. | substring-with-largest-variance | 0 | 1 | # Intuition\nWe have to find maximum difference between occurences of two characters.\n\n\n# Approach\nI used hints to solve the problem.\nI have not used any external library so it must be easy to rewrite in any other language.\nAs there are only 26 chars in alphabets therefore at max 325 combinations or 650 permutati... | 1 | The **variance** of a string is defined as the largest difference between the number of occurrences of **any** `2` characters present in the string. Note the two characters may or may not be the same.
Given a string `s` consisting of lowercase English letters only, return _the **largest variance** possible among all *... | You should test every possible assignment of good and bad people, using a bitmask. In each bitmask, if the person i is good, then his statements should be consistent with the bitmask in order for the assignment to be valid. If the assignment is valid, count how many people are good and keep track of the maximum. |
Python short and clean. Functional programming. | substring-with-largest-variance | 0 | 1 | # Approach\nTL;DR, Similar to [Editorial solution](https://leetcode.com/problems/substring-with-largest-variance/editorial/) but written using functional programming.\n\n# Complexity\n- Time complexity: $$O(n \\cdot k^2)$$\n\n- Space complexity: $$O(k)$$\n\nwhere,\n`n is the length of s`,\n`k is the charset of s. i.e i... | 1 | The **variance** of a string is defined as the largest difference between the number of occurrences of **any** `2` characters present in the string. Note the two characters may or may not be the same.
Given a string `s` consisting of lowercase English letters only, return _the **largest variance** possible among all *... | You should test every possible assignment of good and bad people, using a bitmask. In each bitmask, if the person i is good, then his statements should be consistent with the bitmask in order for the assignment to be valid. If the assignment is valid, count how many people are good and keep track of the maximum. |
Python 🔥Java 🔥C++ 🔥Simple Solution 🔥Easy to Understand | substring-with-largest-variance | 1 | 1 | # An Upvote will be encouraging \uD83D\uDC4D\n\n# Video Solution\n\n# Search \uD83D\uDC49 `Substring With Largest Variance By Tech Wired`\n\n# OR\n\n# Click the link in my profile\n\n# Intuition\n\n- Initialize count1, count2, and max_variance to 0. These variables will keep track of the counts and the maximum variance... | 64 | The **variance** of a string is defined as the largest difference between the number of occurrences of **any** `2` characters present in the string. Note the two characters may or may not be the same.
Given a string `s` consisting of lowercase English letters only, return _the **largest variance** possible among all *... | You should test every possible assignment of good and bad people, using a bitmask. In each bitmask, if the person i is good, then his statements should be consistent with the bitmask in order for the assignment to be valid. If the assignment is valid, count how many people are good and keep track of the maximum. |
"Weird Kadane" | Intuition + Solution Explained | substring-with-largest-variance | 0 | 1 | > **Note you can find the finalised Python3 Code at the very bottom. This post describes how you can start from a standard Kadane\'s Algorithm and end up at the solution [@votrubac describes in his post](https://leetcode.com/problems/substring-with-largest-variance/discuss/2039178/weird-kadane).** @NeosDeus suggested I... | 110 | The **variance** of a string is defined as the largest difference between the number of occurrences of **any** `2` characters present in the string. Note the two characters may or may not be the same.
Given a string `s` consisting of lowercase English letters only, return _the **largest variance** possible among all *... | You should test every possible assignment of good and bad people, using a bitmask. In each bitmask, if the person i is good, then his statements should be consistent with the bitmask in order for the assignment to be valid. If the assignment is valid, count how many people are good and keep track of the maximum. |
Python || Easy Solution || Stack | find-resultant-array-after-removing-anagrams | 0 | 1 | # Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def check(self,word1: str,word2: str)->bool:\n word1=list(word1)\n word1.sort()\n word2=list(word2)\n word2.sort()\n if word1==word2:\n return 1\n return 0\n\... | 1 | You are given a **0-indexed** string array `words`, where `words[i]` consists of lowercase English letters.
In one operation, select any index `i` such that `0 < i < words.length` and `words[i - 1]` and `words[i]` are **anagrams**, and **delete** `words[i]` from `words`. Keep performing this operation as long as you c... | What is the range that the answer must fall into? The answer has to be in the range [0, max(buckets)] (inclusive). For a number x, is there an efficient way to check if it is possible to make the amount of water in each bucket x. Let in be the total amount of water that needs to be poured into buckets and out be the to... |
Python counter || Solution | find-resultant-array-after-removing-anagrams | 0 | 1 | ```\nclass Solution:\n def removeAnagrams(self, words: List[str]) -> List[str]:\n res=[words[0]] \n for i in range(1,len(words)):\n mp1,mp2=Counter(words[i-1]),Counter(words[i]) \n if mp1!=mp2:\n res.append(words[i]) \n return res\n\t\t#misread easy to medium... | 1 | You are given a **0-indexed** string array `words`, where `words[i]` consists of lowercase English letters.
In one operation, select any index `i` such that `0 < i < words.length` and `words[i - 1]` and `words[i]` are **anagrams**, and **delete** `words[i]` from `words`. Keep performing this operation as long as you c... | What is the range that the answer must fall into? The answer has to be in the range [0, max(buckets)] (inclusive). For a number x, is there an efficient way to check if it is possible to make the amount of water in each bucket x. Let in be the total amount of water that needs to be poured into buckets and out be the to... |
itertools is awesome | find-resultant-array-after-removing-anagrams | 0 | 1 | Here\'s a one-liner\n\n```\nclass Solution:\n def removeAnagrams(self, words: List[str]) -> List[str]:\n return (next(val) for _, val in groupby(words, key=sorted))\n``` | 1 | You are given a **0-indexed** string array `words`, where `words[i]` consists of lowercase English letters.
In one operation, select any index `i` such that `0 < i < words.length` and `words[i - 1]` and `words[i]` are **anagrams**, and **delete** `words[i]` from `words`. Keep performing this operation as long as you c... | What is the range that the answer must fall into? The answer has to be in the range [0, max(buckets)] (inclusive). For a number x, is there an efficient way to check if it is possible to make the amount of water in each bucket x. Let in be the total amount of water that needs to be poured into buckets and out be the to... |
Weird Description | find-resultant-array-after-removing-anagrams | 0 | 1 | Misread this question 2 times and wasted like 20 minutes. \n\n**Python 3**\nWanted to bubble-up this solution by one of our humble commenters below (whose name rhymes with batman). \n\nApparently, `itertools.groupby` groups *consecutive* elements by a key (which is `sorted` here). And `next` takes the first element fro... | 48 | You are given a **0-indexed** string array `words`, where `words[i]` consists of lowercase English letters.
In one operation, select any index `i` such that `0 < i < words.length` and `words[i - 1]` and `words[i]` are **anagrams**, and **delete** `words[i]` from `words`. Keep performing this operation as long as you c... | What is the range that the answer must fall into? The answer has to be in the range [0, max(buckets)] (inclusive). For a number x, is there an efficient way to check if it is possible to make the amount of water in each bucket x. Let in be the total amount of water that needs to be poured into buckets and out be the to... |
Python | Easy Solution✅ | find-resultant-array-after-removing-anagrams | 0 | 1 | # Code\u2705\n```\nclass Solution:\n def removeAnagrams(self, words: List[str]) -> List[str]:\n i = 0\n while True:\n if i == len(words)-1:\n break\n if \'\'.join(sorted(words[i])) == \'\'.join(sorted(words[i+1])):\n words.pop(i+1)\n i-... | 6 | You are given a **0-indexed** string array `words`, where `words[i]` consists of lowercase English letters.
In one operation, select any index `i` such that `0 < i < words.length` and `words[i - 1]` and `words[i]` are **anagrams**, and **delete** `words[i]` from `words`. Keep performing this operation as long as you c... | What is the range that the answer must fall into? The answer has to be in the range [0, max(buckets)] (inclusive). For a number x, is there an efficient way to check if it is possible to make the amount of water in each bucket x. Let in be the total amount of water that needs to be poured into buckets and out be the to... |
⛔Remove anagrams || 😐4 liner code || 👍🏻Least complexity... | find-resultant-array-after-removing-anagrams | 0 | 1 | # KARRAR\n>Anagrams...\n>>Removing anagrams...\n>>>Low time complexity...\n>>>>Optimized and generalized solution...\n>>>>> Easy to understand...\n- PLEASE \uD83D\uDC4D\uD83C\uDFFB UPVOTE...\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach:\n Simplest approach...\n ... | 5 | You are given a **0-indexed** string array `words`, where `words[i]` consists of lowercase English letters.
In one operation, select any index `i` such that `0 < i < words.length` and `words[i - 1]` and `words[i]` are **anagrams**, and **delete** `words[i]` from `words`. Keep performing this operation as long as you c... | What is the range that the answer must fall into? The answer has to be in the range [0, max(buckets)] (inclusive). For a number x, is there an efficient way to check if it is possible to make the amount of water in each bucket x. Let in be the total amount of water that needs to be poured into buckets and out be the to... |
C++ - Easiest Beginner Friendly Sol || O(n*m*26) time and O(n*m) space | find-resultant-array-after-removing-anagrams | 1 | 1 | # Intuition of this Problem:\n<!-- Describe your first thoughts on how to solve this problem. -->\n**NOTE - PLEASE READ APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n# Approach for this Problem:\n1. Create a vector called "count" with 26 elements,... | 8 | You are given a **0-indexed** string array `words`, where `words[i]` consists of lowercase English letters.
In one operation, select any index `i` such that `0 < i < words.length` and `words[i - 1]` and `words[i]` are **anagrams**, and **delete** `words[i]` from `words`. Keep performing this operation as long as you c... | What is the range that the answer must fall into? The answer has to be in the range [0, max(buckets)] (inclusive). For a number x, is there an efficient way to check if it is possible to make the amount of water in each bucket x. Let in be the total amount of water that needs to be poured into buckets and out be the to... |
Python 3 | Intuitive + How to approach | O(n) without sorting | find-resultant-array-after-removing-anagrams | 0 | 1 | # Goal\nReturn the list of words after removing anagrams\n\n\n# Approach\n## 1. How do we know if those words have the same anagram? \n\nThose words have the same anagram if the words have the same letters even though they have different orders of letters.\n\n"baby" and "ybba" are anagrams because they have 2b, 1a, and... | 13 | You are given a **0-indexed** string array `words`, where `words[i]` consists of lowercase English letters.
In one operation, select any index `i` such that `0 < i < words.length` and `words[i - 1]` and `words[i]` are **anagrams**, and **delete** `words[i]` from `words`. Keep performing this operation as long as you c... | What is the range that the answer must fall into? The answer has to be in the range [0, max(buckets)] (inclusive). For a number x, is there an efficient way to check if it is possible to make the amount of water in each bucket x. Let in be the total amount of water that needs to be poured into buckets and out be the to... |
python - small & easy to understand solution | find-resultant-array-after-removing-anagrams | 0 | 1 | Runtime: 52 ms, faster than 96.66% of Python3 online submissions for Find Resultant Array After Removing Anagrams.\nMemory Usage: 13.8 MB, less than 75.32% of Python3 online submissions for Find Resultant Array After Removing Anagrams.\n```\nclass Solution:\n def removeAnagrams(self, words: List[str]) -> List[str]:\n ... | 3 | You are given a **0-indexed** string array `words`, where `words[i]` consists of lowercase English letters.
In one operation, select any index `i` such that `0 < i < words.length` and `words[i - 1]` and `words[i]` are **anagrams**, and **delete** `words[i]` from `words`. Keep performing this operation as long as you c... | What is the range that the answer must fall into? The answer has to be in the range [0, max(buckets)] (inclusive). For a number x, is there an efficient way to check if it is possible to make the amount of water in each bucket x. Let in be the total amount of water that needs to be poured into buckets and out be the to... |
Python: Faster than upto 97% quick hashmap/list answer | find-resultant-array-after-removing-anagrams | 0 | 1 | First code submission :D\n\nYou can substitute the hashMap with a list if you\'d like, gives around the same answer time at **77.8%** to as fast as **97%** in one case.\n\n```\nclass Solution:\n def removeAnagrams(self, words: List[str]) -> List[str]:\n #automatically get first word\n hashMap ={0: word... | 1 | You are given a **0-indexed** string array `words`, where `words[i]` consists of lowercase English letters.
In one operation, select any index `i` such that `0 < i < words.length` and `words[i - 1]` and `words[i]` are **anagrams**, and **delete** `words[i]` from `words`. Keep performing this operation as long as you c... | What is the range that the answer must fall into? The answer has to be in the range [0, max(buckets)] (inclusive). For a number x, is there an efficient way to check if it is possible to make the amount of water in each bucket x. Let in be the total amount of water that needs to be poured into buckets and out be the to... |
Python Easy Solution with Comments | find-resultant-array-after-removing-anagrams | 0 | 1 | ```\nclass Solution:\n def removeAnagrams(self, words: List[str]) -> List[str]:\n if len(words) == 1:\n return words\n \n i = 1\n while i < len(words):\n anagram = "".join(sorted(words[i]))\n\t\t\t# check if words[i-1] and words[i] are anagrams\n if anagra... | 5 | You are given a **0-indexed** string array `words`, where `words[i]` consists of lowercase English letters.
In one operation, select any index `i` such that `0 < i < words.length` and `words[i - 1]` and `words[i]` are **anagrams**, and **delete** `words[i]` from `words`. Keep performing this operation as long as you c... | What is the range that the answer must fall into? The answer has to be in the range [0, max(buckets)] (inclusive). For a number x, is there an efficient way to check if it is possible to make the amount of water in each bucket x. Let in be the total amount of water that needs to be poured into buckets and out be the to... |
[Python 3] Sort and pairwise, 3 lines || beats 100% || 555ms 🥷🏼 | maximum-consecutive-floors-without-special-floors | 0 | 1 | ```python3 []\nclass Solution:\n def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> int:\n special.sort()\n res = max((b-a-1 for a, b in pairwise(special)), default = 0)\n\n return max(res, special[0] - bottom, top - special[-1])\n```\n![Screenshot 2023-07-28 at 18.36.49.png]... | 2 | Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be **special floors**, used for relaxation only.
You are given two integers `bottom` and `top`, which denote that Alice has rented all the floors from `bottom` to `top` (**inclusive**). You a... | Repeatedly iterate through the array and check if the current value of original is in the array. If original is not found, stop and return its current value. Otherwise, multiply original by 2 and repeat the process. Use set data structure to check the existence faster. |
Python Easy Solution || 100% || Beats 98.95% || Beginners Friendly || | maximum-consecutive-floors-without-special-floors | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here... | 1 | Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be **special floors**, used for relaxation only.
You are given two integers `bottom` and `top`, which denote that Alice has rented all the floors from `bottom` to `top` (**inclusive**). You a... | Repeatedly iterate through the array and check if the current value of original is in the array. If original is not found, stop and return its current value. Otherwise, multiply original by 2 and repeat the process. Use set data structure to check the existence faster. |
Simple python3 solution | iterate via special + pairwise | maximum-consecutive-floors-without-special-floors | 0 | 1 | # Complexity\n- Time complexity: $$O(n \\cdot log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nclass Solution:\n def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> in... | 1 | Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be **special floors**, used for relaxation only.
You are given two integers `bottom` and `top`, which denote that Alice has rented all the floors from `bottom` to `top` (**inclusive**). You a... | Repeatedly iterate through the array and check if the current value of original is in the array. If original is not found, stop and return its current value. Otherwise, multiply original by 2 and repeat the process. Use set data structure to check the existence faster. |
Python Simulation - Just sort the array special | maximum-consecutive-floors-without-special-floors | 0 | 1 | ```\nclass Solution:\n def maxConsecutive(self, bottom: int, top: int, special: list[int]) -> int:\n special.sort()\n res = special[0] - bottom\n \n for i in range(1, len(special)):\n res = max(res, special[i] - special[i - 1] - 1)\n \n return max(res, top - s... | 7 | Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be **special floors**, used for relaxation only.
You are given two integers `bottom` and `top`, which denote that Alice has rented all the floors from `bottom` to `top` (**inclusive**). You a... | Repeatedly iterate through the array and check if the current value of original is in the array. If original is not found, stop and return its current value. Otherwise, multiply original by 2 and repeat the process. Use set data structure to check the existence faster. |
✔️JAVA || PYTHON ||✔️ 100% || EASY | maximum-consecutive-floors-without-special-floors | 1 | 1 | **SORT THE ARRAY IN INCREASING ORDER**\n\nWE HAVE TO SELECT MAXIMUM VALUE FROM **:**\n* Difference between bottom and least value of array\n* Difference between largest value and top\n* Difference between consecutive values in sorted order -1\n\n\n\n**JAVA**\n```\nclass Solution {\n public int maxConsecutive(int x, ... | 1 | Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be **special floors**, used for relaxation only.
You are given two integers `bottom` and `top`, which denote that Alice has rented all the floors from `bottom` to `top` (**inclusive**). You a... | Repeatedly iterate through the array and check if the current value of original is in the array. If original is not found, stop and return its current value. Otherwise, multiply original by 2 and repeat the process. Use set data structure to check the existence faster. |
Python Simple Solution | Single Iteration | Optimized solution | Difference between floors | maximum-consecutive-floors-without-special-floors | 0 | 1 | ```\nclass Solution:\n def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> int:\n c = 0 \n special.sort()\n c = special[0]-bottom\n bottom = special[0]\n for i in range(1,len(special)):\n if special[i]-bottom>1:\n c = max(c,special[i]-bo... | 2 | Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be **special floors**, used for relaxation only.
You are given two integers `bottom` and `top`, which denote that Alice has rented all the floors from `bottom` to `top` (**inclusive**). You a... | Repeatedly iterate through the array and check if the current value of original is in the array. If original is not found, stop and return its current value. Otherwise, multiply original by 2 and repeat the process. Use set data structure to check the existence faster. |
Check Each Bit | largest-combination-with-bitwise-and-greater-than-zero | 0 | 1 | **Intuition:** we need to count integerts that share the same bit. Bitwise AND of those integers will be positive.\n\nWe count integers that share each bit, and return the maximum.\n\n**Python 3**\n```python\nclass Solution:\n def largestCombination(self, candidates: List[int]) -> int:\n return max(sum(n & (1... | 60 | The **bitwise AND** of an array `nums` is the bitwise AND of all integers in `nums`.
* For example, for `nums = [1, 5, 3]`, the bitwise AND is equal to `1 & 5 & 3 = 1`.
* Also, for `nums = [7]`, the bitwise AND is `7`.
You are given an array of positive integers `candidates`. Evaluate the **bitwise AND** of every... | How can we update the hash value efficiently while iterating instead of recalculating it each time? Use the rolling hash method. |
[Java/Python 3] Bit manipulation w/ explanation and analysis. | largest-combination-with-bitwise-and-greater-than-zero | 1 | 1 | E.g. candidates = [16,17,71,62,12,24,14] \nconvert to binary:\n`[0b1 0000, 0b1 0001, 0b100 0111, 0b11 1110, 0b1100, 0b1 1000, 0b1110]`\n\n1. At `0-th` bit, we have only `17 = 0b1 0001` with `1`, others all have `0` at `0-th` bit, any combination including a number other than `17` in the `candidates` will result a bitwi... | 14 | The **bitwise AND** of an array `nums` is the bitwise AND of all integers in `nums`.
* For example, for `nums = [1, 5, 3]`, the bitwise AND is equal to `1 & 5 & 3 = 1`.
* Also, for `nums = [7]`, the bitwise AND is `7`.
You are given an array of positive integers `candidates`. Evaluate the **bitwise AND** of every... | How can we update the hash value efficiently while iterating instead of recalculating it each time? Use the rolling hash method. |
[Python] Count the Number of Ones at Each Bit, Clean & Concise | largest-combination-with-bitwise-and-greater-than-zero | 0 | 1 | Step 0. Define an array `s` to store the total number of `1`\'s at each bit (reversely);\nStep 1. Convert each `candidate` to binary string;\nStep 2. For each bit, if it is `1`, add it to the array at that bit;\nStep 3. Return the maximum number of 1\u2019s among all possible bits\n\nTime: `O(N * log(10^7))`\nSpace: `O... | 2 | The **bitwise AND** of an array `nums` is the bitwise AND of all integers in `nums`.
* For example, for `nums = [1, 5, 3]`, the bitwise AND is equal to `1 & 5 & 3 = 1`.
* Also, for `nums = [7]`, the bitwise AND is `7`.
You are given an array of positive integers `candidates`. Evaluate the **bitwise AND** of every... | How can we update the hash value efficiently while iterating instead of recalculating it each time? Use the rolling hash method. |
Bitwise AND? Leave it to Python map->sum. | largest-combination-with-bitwise-and-greater-than-zero | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe obvious approach is to enumerate every combination, compute its bitwise-and, count the number of 1 bits, and take the maximum of that over all combinations. Just one problem with this: There are far too many combinations.\n\nFortun... | 0 | The **bitwise AND** of an array `nums` is the bitwise AND of all integers in `nums`.
* For example, for `nums = [1, 5, 3]`, the bitwise AND is equal to `1 & 5 & 3 = 1`.
* Also, for `nums = [7]`, the bitwise AND is `7`.
You are given an array of positive integers `candidates`. Evaluate the **bitwise AND** of every... | How can we update the hash value efficiently while iterating instead of recalculating it each time? Use the rolling hash method. |
Bitwise checking | largest-combination-with-bitwise-and-greater-than-zero | 0 | 1 | \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst find out the largest bit position, then iteratively check the number of 1\'s for each bit position.\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 sp... | 0 | The **bitwise AND** of an array `nums` is the bitwise AND of all integers in `nums`.
* For example, for `nums = [1, 5, 3]`, the bitwise AND is equal to `1 & 5 & 3 = 1`.
* Also, for `nums = [7]`, the bitwise AND is `7`.
You are given an array of positive integers `candidates`. Evaluate the **bitwise AND** of every... | How can we update the hash value efficiently while iterating instead of recalculating it each time? Use the rolling hash method. |
[Python3] SortedList | count-integers-in-intervals | 0 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/5edf72d3865cd9791f0a89b968c0c1aeeaa381c3) for solutions of weekly 293. \n\n```\nfrom sortedcontainers import SortedList\n\nclass CountIntervals:\n\n def __init__(self):\n self.cnt = 0 \n self.intervals = SortedList()\n\n def add... | 27 | Given an **empty** set of intervals, implement a data structure that can:
* **Add** an interval to the set of intervals.
* **Count** the number of integers that are present in **at least one** interval.
Implement the `CountIntervals` class:
* `CountIntervals()` Initializes the object with an empty set of inter... | Can we build a graph from words, where there exists an edge between nodes i and j if words[i] and words[j] are connected? The problem now boils down to finding the total number of components and the size of the largest component in the graph. How can we use bit masking to reduce the search space while adding edges to n... |
[Python3] built-in List beats SortedList | count-integers-in-intervals | 0 | 1 | ### Idea\n1. Initialize list `interv` with `[(-inf, -inf), (inf, inf)]` to store the merged intervals and integer `cov = 0`, to be updated after addition of each interval\n2. Whenever an interval must be added, the following must be done\n- Using binary search, find the range of affected intervals in `interv`, denoted... | 44 | Given an **empty** set of intervals, implement a data structure that can:
* **Add** an interval to the set of intervals.
* **Count** the number of integers that are present in **at least one** interval.
Implement the `CountIntervals` class:
* `CountIntervals()` Initializes the object with an empty set of inter... | Can we build a graph from words, where there exists an edge between nodes i and j if words[i] and words[j] are connected? The problem now boils down to finding the total number of components and the size of the largest component in the graph. How can we use bit masking to reduce the search space while adding edges to n... |
Python3 Sorted List | Merge Intervals in stream | FB follow-up for 56 | count-integers-in-intervals | 0 | 1 | Directly modified from my another post of solution: https://leetcode.com/problems/merge-intervals/discuss/1889983/python-binary-search-solution-for-fb-follow-up-merge-in-stream\n\n#### Original idea\nThis is the idea when I tried to come up with the solution for the follow-up question of 56 with out BST:\n\nThe basic i... | 7 | Given an **empty** set of intervals, implement a data structure that can:
* **Add** an interval to the set of intervals.
* **Count** the number of integers that are present in **at least one** interval.
Implement the `CountIntervals` class:
* `CountIntervals()` Initializes the object with an empty set of inter... | Can we build a graph from words, where there exists an edge between nodes i and j if words[i] and words[j] are connected? The problem now boils down to finding the total number of components and the size of the largest component in the graph. How can we use bit masking to reduce the search space while adding edges to n... |
Python Binary Search | count-integers-in-intervals | 0 | 1 | **Approach**\n1. If there is no intervals yet, just add it and keep track of the count. Otherwise:\n2. Search through intervals for where left of the new interval is less than the end of any interval.\n3. Search through intervals for where right of the new interval is greater than the start of any interval.\n4. If our ... | 10 | Given an **empty** set of intervals, implement a data structure that can:
* **Add** an interval to the set of intervals.
* **Count** the number of integers that are present in **at least one** interval.
Implement the `CountIntervals` class:
* `CountIntervals()` Initializes the object with an empty set of inter... | Can we build a graph from words, where there exists an edge between nodes i and j if words[i] and words[j] are connected? The problem now boils down to finding the total number of components and the size of the largest component in the graph. How can we use bit masking to reduce the search space while adding edges to n... |
Python || merge intervals | count-integers-in-intervals | 0 | 1 | 1. We save non-overlapping intervals by two arrays, `self.L` and `self.R`. `[self.L[i], self.R[i]]` is the `i`th interval.\n2. When a new interval `I = [left, right]` is added, use binary search to find:\n\t- `idx_l`: index of the first interval whose right endpoint >= `left`.\n\t- `idx_r`: index of the first interval ... | 1 | Given an **empty** set of intervals, implement a data structure that can:
* **Add** an interval to the set of intervals.
* **Count** the number of integers that are present in **at least one** interval.
Implement the `CountIntervals` class:
* `CountIntervals()` Initializes the object with an empty set of inter... | Can we build a graph from words, where there exists an edge between nodes i and j if words[i] and words[j] are connected? The problem now boils down to finding the total number of components and the size of the largest component in the graph. How can we use bit masking to reduce the search space while adding edges to n... |
Easy python 3 Solution beats 85%🧑💻💻🤖 | percentage-of-letter-in-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given a string `s` and a character `letter`, return _the **percentage** of characters in_ `s` _that equal_ `letter` _**rounded down** to the nearest whole percent._
**Example 1:**
**Input:** s = "foobar ", letter = "o "
**Output:** 33
**Explanation:**
The percentage of characters in s that equal the letter 'o' is 2... | Notice that if a solution exists, we can represent them as x-1, x, x+1. What does this tell us about the number? Notice the sum of the numbers will be 3x. Can you solve for x? |
python soln | percentage-of-letter-in-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given a string `s` and a character `letter`, return _the **percentage** of characters in_ `s` _that equal_ `letter` _**rounded down** to the nearest whole percent._
**Example 1:**
**Input:** s = "foobar ", letter = "o "
**Output:** 33
**Explanation:**
The percentage of characters in s that equal the letter 'o' is 2... | Notice that if a solution exists, we can represent them as x-1, x, x+1. What does this tell us about the number? Notice the sum of the numbers will be 3x. Can you solve for x? |
[Python ||O(N)] Runtime 50 ms Beats 56.36% Memory 13.9 MB Beats 10.66% | percentage-of-letter-in-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(1)\n<!-- Add your space complexity here, ... | 1 | Given a string `s` and a character `letter`, return _the **percentage** of characters in_ `s` _that equal_ `letter` _**rounded down** to the nearest whole percent._
**Example 1:**
**Input:** s = "foobar ", letter = "o "
**Output:** 33
**Explanation:**
The percentage of characters in s that equal the letter 'o' is 2... | Notice that if a solution exists, we can represent them as x-1, x, x+1. What does this tell us about the number? Notice the sum of the numbers will be 3x. Can you solve for x? |
Simple solution with HashMap in Python3 | percentage-of-letter-in-string | 0 | 1 | # Intuition\nHere we have:\n- string `s` and a `letter` character\n- our goal is find how much percentage (rounded to down) `letter` allocates \n\n# Approach\n1. define a **HashMap**, to store frequencies and find a percentage as `freqOfLetterInS * 100 // len(s)`. \n\n# Complexity\n- Time complexity: **O(N)**, to creat... | 1 | Given a string `s` and a character `letter`, return _the **percentage** of characters in_ `s` _that equal_ `letter` _**rounded down** to the nearest whole percent._
**Example 1:**
**Input:** s = "foobar ", letter = "o "
**Output:** 33
**Explanation:**
The percentage of characters in s that equal the letter 'o' is 2... | Notice that if a solution exists, we can represent them as x-1, x, x+1. What does this tell us about the number? Notice the sum of the numbers will be 3x. Can you solve for x? |
Percentage of letter in string | percentage-of-letter-in-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given a string `s` and a character `letter`, return _the **percentage** of characters in_ `s` _that equal_ `letter` _**rounded down** to the nearest whole percent._
**Example 1:**
**Input:** s = "foobar ", letter = "o "
**Output:** 33
**Explanation:**
The percentage of characters in s that equal the letter 'o' is 2... | Notice that if a solution exists, we can represent them as x-1, x, x+1. What does this tell us about the number? Notice the sum of the numbers will be 3x. Can you solve for x? |
Easy Python Solution | percentage-of-letter-in-string | 0 | 1 | ```\ndef percentageLetter(self, s: str, letter: str) -> int:\n return ("%d" %(s.count(letter)/len(s)*100))\n``` | 4 | Given a string `s` and a character `letter`, return _the **percentage** of characters in_ `s` _that equal_ `letter` _**rounded down** to the nearest whole percent._
**Example 1:**
**Input:** s = "foobar ", letter = "o "
**Output:** 33
**Explanation:**
The percentage of characters in s that equal the letter 'o' is 2... | Notice that if a solution exists, we can represent them as x-1, x, x+1. What does this tell us about the number? Notice the sum of the numbers will be 3x. Can you solve for x? |
Python simple one liner solution | percentage-of-letter-in-string | 0 | 1 | # Code\n```\nclass Solution:\n def percentageLetter(self, s: str, letter: str) -> int:\n return int((s.count(letter) / len(s)) * 100)\n```\n\nLike it ? Please upvote ! | 6 | Given a string `s` and a character `letter`, return _the **percentage** of characters in_ `s` _that equal_ `letter` _**rounded down** to the nearest whole percent._
**Example 1:**
**Input:** s = "foobar ", letter = "o "
**Output:** 33
**Explanation:**
The percentage of characters in s that equal the letter 'o' is 2... | Notice that if a solution exists, we can represent them as x-1, x, x+1. What does this tell us about the number? Notice the sum of the numbers will be 3x. Can you solve for x? |
[Python] Priority queue; Explained | maximum-bags-with-full-capacity-of-rocks | 0 | 1 | We just need to calculate the number of missing rocks for each of the bag;\nPlace the additional rocks into the bag that need the least number of rocks.\n\nWe can use a min heap/priority queue to sort the bags based on the missing rocks.\n\n```\nimport heapq\n\nclass Solution:\n def maximumBags(self, capacity: List[... | 2 | You have `n` bags numbered from `0` to `n - 1`. You are given two **0-indexed** integer arrays `capacity` and `rocks`. The `ith` bag can hold a maximum of `capacity[i]` rocks and currently contains `rocks[i]` rocks. You are also given an integer `additionalRocks`, the number of additional rocks you can place in **any**... | First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the fir... |
Python 1-liner | maximum-bags-with-full-capacity-of-rocks | 0 | 1 | We always want to fill the bags closest to being full, so sort bags by the number of spaces left. Then compute prefix sum to find cumulative number of spaces left. Finally, perform a binary search to find the index where our cumulative sum is <= the number of additional rocks.\n\n# Complexity\n- Time complexity:\n<!-- ... | 2 | You have `n` bags numbered from `0` to `n - 1`. You are given two **0-indexed** integer arrays `capacity` and `rocks`. The `ith` bag can hold a maximum of `capacity[i]` rocks and currently contains `rocks[i]` rocks. You are also given an integer `additionalRocks`, the number of additional rocks you can place in **any**... | First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the fir... |
Python | Functional Style and Readability | maximum-bags-with-full-capacity-of-rocks | 0 | 1 | # Intuition\n\nIt\'s easiest to fill up bags that are closest to being full.\n\n# Approach\n\n1. First of all, find the `free` space in each bag as `capacity[i] - rocks[i]`. It is rather obvious that one can use `zip` to avoid iteration by index. You may further recall that `operator.sub` can perform subtraction. The t... | 2 | You have `n` bags numbered from `0` to `n - 1`. You are given two **0-indexed** integer arrays `capacity` and `rocks`. The `ith` bag can hold a maximum of `capacity[i]` rocks and currently contains `rocks[i]` rocks. You are also given an integer `additionalRocks`, the number of additional rocks you can place in **any**... | First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the fir... |
Beats 100% | CodeDominar Solution | maximum-bags-with-full-capacity-of-rocks | 0 | 1 | # Code\n```\nclass Solution:\n def maximumBags(self, capacity: List[int], rocks: List[int], additionalRocks: int) -> int:\n # Calculate the vacant space in each bag\n vacant = []\n for a, b in zip(capacity, rocks):\n vacant.append(a - b)\n\n # Sort the list of vacant spaces in ... | 2 | You have `n` bags numbered from `0` to `n - 1`. You are given two **0-indexed** integer arrays `capacity` and `rocks`. The `ith` bag can hold a maximum of `capacity[i]` rocks and currently contains `rocks[i]` rocks. You are also given an integer `additionalRocks`, the number of additional rocks you can place in **any**... | First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the fir... |
Fastest PYTHON SOLUTION | maximum-bags-with-full-capacity-of-rocks | 0 | 1 | # Intuition\nMy thought behind this logic is that I want to fill up the bags first that needs less additional rocks to full the bags\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nIt\'s the greedy approach, sort the bags with their difference between full capacity and current filled... | 2 | You have `n` bags numbered from `0` to `n - 1`. You are given two **0-indexed** integer arrays `capacity` and `rocks`. The `ith` bag can hold a maximum of `capacity[i]` rocks and currently contains `rocks[i]` rocks. You are also given an integer `additionalRocks`, the number of additional rocks you can place in **any**... | First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the fir... |
Easy solution | O(nlogn) TC | O(1) SC | maximum-bags-with-full-capacity-of-rocks | 0 | 1 | ```\nclass Solution:\n def maximumBags(self, capacity: List[int], rocks: List[int], additionalRocks: int) -> int:\n for i in range(len(capacity)):\n capacity[i] -= rocks[i]\n \n capacity.sort()\n for i in range(len(capacity)):\n if capacity[i] > additionalRocks:\... | 4 | You have `n` bags numbered from `0` to `n - 1`. You are given two **0-indexed** integer arrays `capacity` and `rocks`. The `ith` bag can hold a maximum of `capacity[i]` rocks and currently contains `rocks[i]` rocks. You are also given an integer `additionalRocks`, the number of additional rocks you can place in **any**... | First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the fir... |
Python 3-lines efficient solution | maximum-bags-with-full-capacity-of-rocks | 0 | 1 | # Intuition\nIt\'s easy\n\n# Approach\nSort difference, iterate while we can use additionalRocks\n\n# Complexity\n- Time complexity:\n$$O(N*logN)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def maximumBags(self, capacity: List[int], rocks: List[int], aRocks=1) -> int:\n bags, n, l = sorted(... | 1 | You have `n` bags numbered from `0` to `n - 1`. You are given two **0-indexed** integer arrays `capacity` and `rocks`. The `ith` bag can hold a maximum of `capacity[i]` rocks and currently contains `rocks[i]` rocks. You are also given an integer `additionalRocks`, the number of additional rocks you can place in **any**... | First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the fir... |
✅ 100% beats || Python3 || ☢️ Sort ☢️ || understandable code | maximum-bags-with-full-capacity-of-rocks | 0 | 1 | Link submission:\nhttps://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/submissions/1125068163\n\n# Intuition\nReceiving the maximum number of bags which fulled with rocks is involved in the problem.There are $$capacity$$ and $$rocks$$ lists given.The former represents the capasity of n bags in rocks. ... | 1 | You have `n` bags numbered from `0` to `n - 1`. You are given two **0-indexed** integer arrays `capacity` and `rocks`. The `ith` bag can hold a maximum of `capacity[i]` rocks and currently contains `rocks[i]` rocks. You are also given an integer `additionalRocks`, the number of additional rocks you can place in **any**... | First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the fir... |
2279. Maximum Bags With Full Capacity of Rocks --> Python easy Soln | maximum-bags-with-full-capacity-of-rocks | 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 O(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O... | 1 | You have `n` bags numbered from `0` to `n - 1`. You are given two **0-indexed** integer arrays `capacity` and `rocks`. The `ith` bag can hold a maximum of `capacity[i]` rocks and currently contains `rocks[i]` rocks. You are also given an integer `additionalRocks`, the number of additional rocks you can place in **any**... | First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the fir... |
Python Solution Explained ✅ | O(n) | maximum-bags-with-full-capacity-of-rocks | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince the problem asks us for the count off filed bags it is better to create an array of difference between current and max capacity\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe first create an array `diffBag`... | 1 | You have `n` bags numbered from `0` to `n - 1`. You are given two **0-indexed** integer arrays `capacity` and `rocks`. The `ith` bag can hold a maximum of `capacity[i]` rocks and currently contains `rocks[i]` rocks. You are also given an integer `additionalRocks`, the number of additional rocks you can place in **any**... | First, check if finalSum is divisible by 2. If it isn’t, then we cannot split it into even integers. Let k be the number of elements in our split. As we want the maximum number of elements, we should try to use the first k - 1 even elements to grow our sum as slowly as possible. Thus, we find the maximum sum of the fir... |
Python Easy Solution || Cross Product | minimum-lines-to-represent-a-line-chart | 0 | 1 | # Code\n```\nclass Solution:\n def minimumLines(self, stockPrices: List[List[int]]) -> int:\n stockPrices.sort()\n line=1\n if len(stockPrices)==1:\n return 0\n for i in range(1,len(stockPrices)-1):\n if (stockPrices[i][1]-stockPrices[i-1][1])*(stockPrices[i+1][0]-st... | 1 | You are given a 2D integer array `stockPrices` where `stockPrices[i] = [dayi, pricei]` indicates the price of the stock on day `dayi` is `pricei`. A **line chart** is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting ad... | For every value y, how can you find the number of values x (0 ≤ x, y ≤ n - 1) such that x appears before y in both of the arrays? Similarly, for every value y, try finding the number of values z (0 ≤ y, z ≤ n - 1) such that z appears after y in both of the arrays. Now, for every value y, count the number of good tripl... |
Python | Easy to Understand | minimum-lines-to-represent-a-line-chart | 0 | 1 | ```\nclass Solution:\n def minimumLines(self, stockPrices: List[List[int]]) -> int:\n # key point: never use devision to judge whether 3 points are on a same line or not, use the multiplication instead !!\n \n n = len(stockPrices)\n stockPrices.sort(key = lambda x: (x[0], x[1]))\n ... | 12 | You are given a 2D integer array `stockPrices` where `stockPrices[i] = [dayi, pricei]` indicates the price of the stock on day `dayi` is `pricei`. A **line chart** is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting ad... | For every value y, how can you find the number of values x (0 ≤ x, y ≤ n - 1) such that x appears before y in both of the arrays? Similarly, for every value y, try finding the number of values z (0 ≤ y, z ≤ n - 1) such that z appears after y in both of the arrays. Now, for every value y, count the number of good tripl... |
PYTHON SIMPLE SOLUTION | EASY TO UNDERSTAND LOGIC | SORTING | minimum-lines-to-represent-a-line-chart | 0 | 1 | ```\nclass Solution:\n def minimumLines(self, stockPrices: List[List[int]]) -> int:\n if len(stockPrices) == 1:\n return 0\n stockPrices.sort(key = lambda x: x[0])\n ans = 1\n for i in range(1,len(stockPrices)-1):\n if (stockPrices[i+1][1]-stockPrices[i][1])*(stockPr... | 2 | You are given a 2D integer array `stockPrices` where `stockPrices[i] = [dayi, pricei]` indicates the price of the stock on day `dayi` is `pricei`. A **line chart** is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting ad... | For every value y, how can you find the number of values x (0 ≤ x, y ≤ n - 1) such that x appears before y in both of the arrays? Similarly, for every value y, try finding the number of values z (0 ≤ y, z ≤ n - 1) such that z appears after y in both of the arrays. Now, for every value y, count the number of good tripl... |
Python Solution || O(nlogn) | minimum-lines-to-represent-a-line-chart | 0 | 1 | ```\nfrom fractions import Fraction # For larger values it will give accurate answer\nclass Solution:\n def minimumLines(self, stockPrices: List[List[int]]) -> int:\n l=[]\n stockPrices.sort()\n c=None\n k=0\n for i,j in pairwise(stockPrices):\n x=Fraction(j[1... | 1 | You are given a 2D integer array `stockPrices` where `stockPrices[i] = [dayi, pricei]` indicates the price of the stock on day `dayi` is `pricei`. A **line chart** is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting ad... | For every value y, how can you find the number of values x (0 ≤ x, y ≤ n - 1) such that x appears before y in both of the arrays? Similarly, for every value y, try finding the number of values z (0 ≤ y, z ≤ n - 1) such that z appears after y in both of the arrays. Now, for every value y, count the number of good tripl... |
This problem needs to labelled as "banished at interviews", "Ok for education/competions" | sum-of-total-strength-of-wizards | 0 | 1 | # Intuition(what I think about this problem)\n\nI think there should be a label on such problems like "Educational" or something like "Not a great interview problem unless you have 2 hours". I think the idea of asking coding problems at interviews should be to test weather a candidate can come up with multiple solution... | 1 | As the ruler of a kingdom, you have an army of wizards at your command.
You are given a **0-indexed** integer array `strength`, where `strength[i]` denotes the strength of the `ith` wizard. For a **contiguous** group of wizards (i.e. the wizards' strengths form a **subarray** of `strength`), the **total strength** is ... | null |
[Python] "Geometric" Solution | sum-of-total-strength-of-wizards | 0 | 1 | # Intuition\nI thought it would be fun to do an array-based solution that does not utilize a conventional stack approach. It isn\'t the fastest but I find it interesting. \n# Approach\nThe number of occurrences of a value across all contiguous subarrays is given with position index array $$pos$$ is given by:\n\n$$count... | 1 | As the ruler of a kingdom, you have an army of wizards at your command.
You are given a **0-indexed** integer array `strength`, where `strength[i]` denotes the strength of the `ith` wizard. For a **contiguous** group of wizards (i.e. the wizards' strengths form a **subarray** of `strength`), the **total strength** is ... | null |
Python simplest O(n) full derivation | sum-of-total-strength-of-wizards | 0 | 1 | Let `s = strength`, `p[k]=s[0] + ... + s[k]` be the prefix sum of `s`, `pp[k]=p[0] + ... + p[k]` be the sum of prefix sums. We want to derive `t[k]` denoting total sum of strengths of wizards ending at index `k`. We would like to keep indices of `s` minimums in monotonic increasing stack e.g. `s = [1, 2, 3, 2, 5]` then... | 0 | As the ruler of a kingdom, you have an army of wizards at your command.
You are given a **0-indexed** integer array `strength`, where `strength[i]` denotes the strength of the `ith` wizard. For a **contiguous** group of wizards (i.e. the wizards' strengths form a **subarray** of `strength`), the **total strength** is ... | null |
[Easty Python ] | check-if-number-has-equal-digit-count-and-digit-value | 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- wrost O(N^2)\n- best O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(1)\n<!-- Add your sp... | 1 | You are given a **0-indexed** string `num` of length `n` consisting of digits.
Return `true` _if for **every** index_ `i` _in the range_ `0 <= i < n`_, the digit_ `i` _occurs_ `num[i]` _times in_ `num`_, otherwise return_ `false`.
**Example 1:**
**Input:** num = "1210 "
**Output:** true
**Explanation:**
num\[0\] = ... | Try to separate the elements at odd indices from the elements at even indices. Sort the two groups of elements individually. Combine them to form the resultant array. |
Easy Python3 Solution using Count | check-if-number-has-equal-digit-count-and-digit-value | 0 | 1 | \n# Code\n```\nclass Solution:\n def digitCount(self, num: str) -> bool:\n for i in range(len(num)):\n if int(num[i]) != num.count(str(i)):\n return False\n return True\n``` | 7 | You are given a **0-indexed** string `num` of length `n` consisting of digits.
Return `true` _if for **every** index_ `i` _in the range_ `0 <= i < n`_, the digit_ `i` _occurs_ `num[i]` _times in_ `num`_, otherwise return_ `false`.
**Example 1:**
**Input:** num = "1210 "
**Output:** true
**Explanation:**
num\[0\] = ... | Try to separate the elements at odd indices from the elements at even indices. Sort the two groups of elements individually. Combine them to form the resultant array. |
Python Beginner Friendly Explanation Beats - 91% | check-if-number-has-equal-digit-count-and-digit-value | 0 | 1 | # Approach\nSimple Compare the count of current index with value at corrent index\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(1)\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... | 1 | You are given a **0-indexed** string `num` of length `n` consisting of digits.
Return `true` _if for **every** index_ `i` _in the range_ `0 <= i < n`_, the digit_ `i` _occurs_ `num[i]` _times in_ `num`_, otherwise return_ `false`.
**Example 1:**
**Input:** num = "1210 "
**Output:** true
**Explanation:**
num\[0\] = ... | Try to separate the elements at odd indices from the elements at even indices. Sort the two groups of elements individually. Combine them to form the resultant array. |
Easy Python solution | check-if-number-has-equal-digit-count-and-digit-value | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def digitCount(self, num: str) -> bool:\n for i in range(len(num)):\n if num.count(str(i)) != int(num[i]):\n return False\n return True \n``` | 1 | You are given a **0-indexed** string `num` of length `n` consisting of digits.
Return `true` _if for **every** index_ `i` _in the range_ `0 <= i < n`_, the digit_ `i` _occurs_ `num[i]` _times in_ `num`_, otherwise return_ `false`.
**Example 1:**
**Input:** num = "1210 "
**Output:** true
**Explanation:**
num\[0\] = ... | Try to separate the elements at odd indices from the elements at even indices. Sort the two groups of elements individually. Combine them to form the resultant array. |
Easy approach for beginners : time complexity : O(n) | check-if-number-has-equal-digit-count-and-digit-value | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $... | 1 | You are given a **0-indexed** string `num` of length `n` consisting of digits.
Return `true` _if for **every** index_ `i` _in the range_ `0 <= i < n`_, the digit_ `i` _occurs_ `num[i]` _times in_ `num`_, otherwise return_ `false`.
**Example 1:**
**Input:** num = "1210 "
**Output:** true
**Explanation:**
num\[0\] = ... | Try to separate the elements at odd indices from the elements at even indices. Sort the two groups of elements individually. Combine them to form the resultant array. |
Easy Python Solution | check-if-number-has-equal-digit-count-and-digit-value | 0 | 1 | ```\ndef digitCount(self, num: str) -> bool:\n for i in range(len(num)):\n if num.count(str(i))!=int(num[i]):\n return False\n return True\n``` | 4 | You are given a **0-indexed** string `num` of length `n` consisting of digits.
Return `true` _if for **every** index_ `i` _in the range_ `0 <= i < n`_, the digit_ `i` _occurs_ `num[i]` _times in_ `num`_, otherwise return_ `false`.
**Example 1:**
**Input:** num = "1210 "
**Output:** true
**Explanation:**
num\[0\] = ... | Try to separate the elements at odd indices from the elements at even indices. Sort the two groups of elements individually. Combine them to form the resultant array. |
Python3 very elegant and straightforward | check-if-number-has-equal-digit-count-and-digit-value | 0 | 1 | \n```\n c = Counter(num)\n for idx, x in enumerate(num):\n if c[str(idx)] != int(x):\n return False\n return True\n``` | 2 | You are given a **0-indexed** string `num` of length `n` consisting of digits.
Return `true` _if for **every** index_ `i` _in the range_ `0 <= i < n`_, the digit_ `i` _occurs_ `num[i]` _times in_ `num`_, otherwise return_ `false`.
**Example 1:**
**Input:** num = "1210 "
**Output:** true
**Explanation:**
num\[0\] = ... | Try to separate the elements at odd indices from the elements at even indices. Sort the two groups of elements individually. Combine them to form the resultant array. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.