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 |
|---|---|---|---|---|---|---|---|
[Java/Python 3] From O(n ^ (1 / 3)) to O(log(n)), easy codes w/ brief explanation & analysis. | minimum-garden-perimeter-to-collect-enough-apples | 1 | 1 | **Method 1:**\n\nDivide into 3 parts: axis, corner and other:\n\nUse `i`, `corner` and `other` to denote the number of apples on each half axis, each corner and other parts, respectively.\n\nObviously, for any given `i`, each half axis has `i` apples; each of the 4 corners has `2 * i` apples, and the rest part (quadra... | 10 | Given an array `nums` of integers, return how many of them contain an **even number** of digits.
**Example 1:**
**Input:** nums = \[12,345,2,6,7896\]
**Output:** 2
**Explanation:**
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).... | Find a formula for the number of apples inside a square with a side length L. Iterate over the possible lengths of the square until enough apples are collected. |
Easy python solution | minimum-garden-perimeter-to-collect-enough-apples | 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 | In a garden represented as an infinite 2D grid, there is an apple tree planted at **every** integer coordinate. The apple tree planted at an integer coordinate `(i, j)` has `|i| + |j|` apples growing on it.
You will buy an axis-aligned **square plot** of land that is centered at `(0, 0)`.
Given an integer `neededAppl... | We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position |
Easy python solution | minimum-garden-perimeter-to-collect-enough-apples | 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 | Given an array `nums` of integers, return how many of them contain an **even number** of digits.
**Example 1:**
**Input:** nums = \[12,345,2,6,7896\]
**Output:** 2
**Explanation:**
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).... | Find a formula for the number of apples inside a square with a side length L. Iterate over the possible lengths of the square until enough apples are collected. |
Python3 | Binary Search solution | minimum-garden-perimeter-to-collect-enough-apples | 0 | 1 | \n# Code\n```\nclass Solution:\n def minimumPerimeter(self, neededApples: int) -> int:\n i = 0\n l = 1;r = 10**15\n while l<r:\n m = (l+r)//2\n if neededApples<=check(m):\n r = m\n else:\n l = m+1\n return l*8\n\n\n\n\ndef che... | 0 | In a garden represented as an infinite 2D grid, there is an apple tree planted at **every** integer coordinate. The apple tree planted at an integer coordinate `(i, j)` has `|i| + |j|` apples growing on it.
You will buy an axis-aligned **square plot** of land that is centered at `(0, 0)`.
Given an integer `neededAppl... | We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position |
Python3 | Binary Search solution | minimum-garden-perimeter-to-collect-enough-apples | 0 | 1 | \n# Code\n```\nclass Solution:\n def minimumPerimeter(self, neededApples: int) -> int:\n i = 0\n l = 1;r = 10**15\n while l<r:\n m = (l+r)//2\n if neededApples<=check(m):\n r = m\n else:\n l = m+1\n return l*8\n\n\n\n\ndef che... | 0 | Given an array `nums` of integers, return how many of them contain an **even number** of digits.
**Example 1:**
**Input:** nums = \[12,345,2,6,7896\]
**Output:** 2
**Explanation:**
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).... | Find a formula for the number of apples inside a square with a side length L. Iterate over the possible lengths of the square until enough apples are collected. |
Fully Explained **MADE EASY** | minimum-garden-perimeter-to-collect-enough-apples | 0 | 1 | \n\n\n\n\n# Complexity\n- Time complexity:\nO(neededapples)\n\n- Space complexity:\nO(1)\n\n... | 0 | In a garden represented as an infinite 2D grid, there is an apple tree planted at **every** integer coordinate. The apple tree planted at an integer coordinate `(i, j)` has `|i| + |j|` apples growing on it.
You will buy an axis-aligned **square plot** of land that is centered at `(0, 0)`.
Given an integer `neededAppl... | We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position |
Fully Explained **MADE EASY** | minimum-garden-perimeter-to-collect-enough-apples | 0 | 1 | \n\n\n\n\n# Complexity\n- Time complexity:\nO(neededapples)\n\n- Space complexity:\nO(1)\n\n... | 0 | Given an array `nums` of integers, return how many of them contain an **even number** of digits.
**Example 1:**
**Input:** nums = \[12,345,2,6,7896\]
**Output:** 2
**Explanation:**
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).... | Find a formula for the number of apples inside a square with a side length L. Iterate over the possible lengths of the square until enough apples are collected. |
Simple Python with comments. One pass O(n) with O(1) space | count-number-of-special-subsequences | 0 | 1 | ```\nclass Solution:\n def countSpecialSubsequences(self, nums: List[int]) -> int:\n total_zeros = 0 # number of subsequences of 0s so far\n total_ones = 0 # the number of subsequences of 0s followed by 1s so far\n total_twos = 0 # the number of special subsequences so far\n \n M =... | 4 | A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s.
* For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special.
* In contrast, `[2,1,0]`, `[1]`, and `[0,1,2,0]` are not special.
Given an array `nums` (consisting of... | You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an eleme... |
Python (Simple Maths) | count-number-of-special-subsequences | 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 | A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s.
* For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special.
* In contrast, `[2,1,0]`, `[1]`, and `[0,1,2,0]` are not special.
Given an array `nums` (consisting of... | You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an eleme... |
Python easy to read and understand | dp | count-number-of-special-subsequences | 0 | 1 | ```\nclass Solution:\n def countSpecialSubsequences(self, nums: List[int]) -> int:\n t, mod = [0]*3, 10**9 + 7\n \n for num in nums:\n if num == 0:\n t[0] = t[0]*2 + 1\n elif num == 1:\n t[1] = t[1]*2 + t[0]\n else:\n ... | 0 | A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s.
* For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special.
* In contrast, `[2,1,0]`, `[1]`, and `[0,1,2,0]` are not special.
Given an array `nums` (consisting of... | You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an eleme... |
python3 Solution | count-number-of-special-subsequences | 0 | 1 | \n```\nclass Solution:\n def countSpecialSubsequences(self, nums: List[int]) -> int:\n dp=[0]*3\n for num in nums:\n if num==0:\n dp[0]=2*dp[0]+1\n\n else:\n dp[num]=dp[num-1]+2*dp[num]\n\n mod=10**9+7\n return dp[2]%mod \n``` | 0 | A sequence is **special** if it consists of a **positive** number of `0`s, followed by a **positive** number of `1`s, then a **positive** number of `2`s.
* For example, `[0,1,2]` and `[0,0,1,1,1,2]` are special.
* In contrast, `[2,1,0]`, `[1]`, and `[0,1,2,0]` are not special.
Given an array `nums` (consisting of... | You need a data structure that maintains the states of the seats. This data structure should also allow you to get the first available seat and flip the state of a seat in a reasonable time. You can let the data structure contain the available seats. Then you want to be able to get the lowest element and erase an eleme... |
[Java/Python 3] Count, put into StringBuilder/list and join it. | delete-characters-to-make-fancy-string | 1 | 1 | Count consecutive same characters, if less than `3`, put into `StringBuilder/List`; Otherwise, ignore it.\n```java\n public String makeFancyString(String s) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0, cnt = 0; i < s.length(); ++i) {\n if (i > 0 && s.charAt(i - 1) == s.char... | 19 | A **fancy string** is a string where no **three** **consecutive** characters are equal.
Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**.
Return _the final string after the deletion_. It can be shown that the answer will always be **unique**.
**Example 1:**
**In... | Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time. |
[Java/Python 3] Count, put into StringBuilder/list and join it. | delete-characters-to-make-fancy-string | 1 | 1 | Count consecutive same characters, if less than `3`, put into `StringBuilder/List`; Otherwise, ignore it.\n```java\n public String makeFancyString(String s) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0, cnt = 0; i < s.length(); ++i) {\n if (i > 0 && s.charAt(i - 1) == s.char... | 19 | Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes i... | What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest. |
Python | Easy Solution✅ | delete-characters-to-make-fancy-string | 0 | 1 | # Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\u2705\n```\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n stack = []\n for letter in s:\n if len(stack) > 1 and letter == stack[-1] == stack[-2]:\n stack.pop(... | 10 | A **fancy string** is a string where no **three** **consecutive** characters are equal.
Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**.
Return _the final string after the deletion_. It can be shown that the answer will always be **unique**.
**Example 1:**
**In... | Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time. |
Python | Easy Solution✅ | delete-characters-to-make-fancy-string | 0 | 1 | # Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\u2705\n```\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n stack = []\n for letter in s:\n if len(stack) > 1 and letter == stack[-1] == stack[-2]:\n stack.pop(... | 10 | Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes i... | What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest. |
Very simple solution. Runtime 99.41%!!! | delete-characters-to-make-fancy-string | 0 | 1 | \n# Code\n```\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n\n ans, last, count = [], "", 0\n for ch in s:\n if ch == last:\n count += 1\n else:\n count = 0\n if count < 2:\n ans.append(ch)\n last =... | 1 | A **fancy string** is a string where no **three** **consecutive** characters are equal.
Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**.
Return _the final string after the deletion_. It can be shown that the answer will always be **unique**.
**Example 1:**
**In... | Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time. |
Very simple solution. Runtime 99.41%!!! | delete-characters-to-make-fancy-string | 0 | 1 | \n# Code\n```\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n\n ans, last, count = [], "", 0\n for ch in s:\n if ch == last:\n count += 1\n else:\n count = 0\n if count < 2:\n ans.append(ch)\n last =... | 1 | Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes i... | What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest. |
[Python3] stack | delete-characters-to-make-fancy-string | 0 | 1 | \n```\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n stack = []\n for ch in s: \n if len(stack) > 1 and stack[-2] == stack[-1] == ch: continue \n stack.append(ch)\n return "".join(stack)\n``` | 9 | A **fancy string** is a string where no **three** **consecutive** characters are equal.
Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**.
Return _the final string after the deletion_. It can be shown that the answer will always be **unique**.
**Example 1:**
**In... | Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time. |
[Python3] stack | delete-characters-to-make-fancy-string | 0 | 1 | \n```\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n stack = []\n for ch in s: \n if len(stack) > 1 and stack[-2] == stack[-1] == ch: continue \n stack.append(ch)\n return "".join(stack)\n``` | 9 | Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes i... | What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest. |
This my simple solution | delete-characters-to-make-fancy-string | 0 | 1 | ```\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n if len(s) < 3:\n return s\n ans = \'\'\n ans += s[0]\n ans += s[1]\n for i in range(2,len(s)):\n if s[i] != ans[-1] or s[i] != ans[-2]:\n ans += s[i]\n return ans\n``` | 4 | A **fancy string** is a string where no **three** **consecutive** characters are equal.
Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**.
Return _the final string after the deletion_. It can be shown that the answer will always be **unique**.
**Example 1:**
**In... | Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time. |
This my simple solution | delete-characters-to-make-fancy-string | 0 | 1 | ```\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n if len(s) < 3:\n return s\n ans = \'\'\n ans += s[0]\n ans += s[1]\n for i in range(2,len(s)):\n if s[i] != ans[-1] or s[i] != ans[-2]:\n ans += s[i]\n return ans\n``` | 4 | Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes i... | What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest. |
Python count during traversal | delete-characters-to-make-fancy-string | 0 | 1 | # Code\n```\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n cnt = 0\n res = []\n\n for i, c in enumerate(s):\n if i == 0:\n cnt += 1\n elif i > 0 and c == s[i - 1]:\n cnt += 1\n elif i > 0 and c != s[i - 1]:\n ... | 0 | A **fancy string** is a string where no **three** **consecutive** characters are equal.
Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**.
Return _the final string after the deletion_. It can be shown that the answer will always be **unique**.
**Example 1:**
**In... | Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time. |
Python count during traversal | delete-characters-to-make-fancy-string | 0 | 1 | # Code\n```\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n cnt = 0\n res = []\n\n for i, c in enumerate(s):\n if i == 0:\n cnt += 1\n elif i > 0 and c == s[i - 1]:\n cnt += 1\n elif i > 0 and c != s[i - 1]:\n ... | 0 | Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes i... | What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest. |
Python stack (not that easy for me) | delete-characters-to-make-fancy-string | 0 | 1 | # Code\n```\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n stack = []\n\n for c in s:\n if len(stack) >= 2 and stack[-1] == stack[-2] == c:\n stack.pop()\n \n stack.append(c)\n \n return \'\'.join(stack)\n``` | 0 | A **fancy string** is a string where no **three** **consecutive** characters are equal.
Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**.
Return _the final string after the deletion_. It can be shown that the answer will always be **unique**.
**Example 1:**
**In... | Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time. |
Python stack (not that easy for me) | delete-characters-to-make-fancy-string | 0 | 1 | # Code\n```\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n stack = []\n\n for c in s:\n if len(stack) >= 2 and stack[-1] == stack[-2] == c:\n stack.pop()\n \n stack.append(c)\n \n return \'\'.join(stack)\n``` | 0 | Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes i... | What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest. |
python | delete-characters-to-make-fancy-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)$$ --... | 0 | A **fancy string** is a string where no **three** **consecutive** characters are equal.
Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**.
Return _the final string after the deletion_. It can be shown that the answer will always be **unique**.
**Example 1:**
**In... | Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time. |
python | delete-characters-to-make-fancy-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)$$ --... | 0 | Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes i... | What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest. |
Regular Expressions | delete-characters-to-make-fancy-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)$$ --... | 0 | A **fancy string** is a string where no **three** **consecutive** characters are equal.
Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**.
Return _the final string after the deletion_. It can be shown that the answer will always be **unique**.
**Example 1:**
**In... | Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time. |
Regular Expressions | delete-characters-to-make-fancy-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)$$ --... | 0 | Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes i... | What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest. |
Python & Rust Solutions | delete-characters-to-make-fancy-string | 0 | 1 | # Code\n```python []\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n result = ""\n for c in s:\n if result.endswith(c * 2):\n continue\n result += c\n return result\n```\n```rust []\nimpl Solution {\n pub fn make_fancy_string(s: String) -> S... | 0 | A **fancy string** is a string where no **three** **consecutive** characters are equal.
Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**.
Return _the final string after the deletion_. It can be shown that the answer will always be **unique**.
**Example 1:**
**In... | Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time. |
Python & Rust Solutions | delete-characters-to-make-fancy-string | 0 | 1 | # Code\n```python []\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n result = ""\n for c in s:\n if result.endswith(c * 2):\n continue\n result += c\n return result\n```\n```rust []\nimpl Solution {\n pub fn make_fancy_string(s: String) -> S... | 0 | Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes i... | What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest. |
Beats 91.63% of users with Python3 | delete-characters-to-make-fancy-string | 0 | 1 | # Code\n```\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n # bruteforce solutions\n # 377ms\n # Beats 83.49% of users with Python3\n """\n from itertools import groupby\n ret = ""\n for k, v in groupby(s):\n n = len(list(v))\n if ... | 0 | A **fancy string** is a string where no **three** **consecutive** characters are equal.
Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**.
Return _the final string after the deletion_. It can be shown that the answer will always be **unique**.
**Example 1:**
**In... | Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time. |
Beats 91.63% of users with Python3 | delete-characters-to-make-fancy-string | 0 | 1 | # Code\n```\nclass Solution:\n def makeFancyString(self, s: str) -> str:\n # bruteforce solutions\n # 377ms\n # Beats 83.49% of users with Python3\n """\n from itertools import groupby\n ret = ""\n for k, v in groupby(s):\n n = len(list(v))\n if ... | 0 | Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes i... | What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest. |
python easy solution | delete-characters-to-make-fancy-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)$$ --... | 0 | A **fancy string** is a string where no **three** **consecutive** characters are equal.
Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**.
Return _the final string after the deletion_. It can be shown that the answer will always be **unique**.
**Example 1:**
**In... | Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time. |
python easy solution | delete-characters-to-make-fancy-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)$$ --... | 0 | Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes i... | What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest. |
Python 3 || 11 lines, w/ comments || T/M: 95% / 99% | check-if-move-is-legal | 0 | 1 | Pretty much the same eight-direction approach as other posted solutions, but with one additional twist. We construct a border of`["."]`cells around the`board`. Having this border reduces the number of states to be tested to determine whether a specific direction yields a legal move.\n```\nclass Solution:\n def check... | 3 | You are given a **0-indexed** `8 x 8` grid `board`, where `board[r][c]` represents the cell `(r, c)` on a game board. On the board, free cells are represented by `'.'`, white cells are represented by `'W'`, and black cells are represented by `'B'`.
Each move in this game consists of choosing a free cell and changing i... | null |
[Java/Python 3]Check 8 directions. | check-if-move-is-legal | 1 | 1 | **Q & A**\n\nQ1: Why `size` is initialized to `2`?\nA1: We actually check the cells starting from the `2nd` one, and the first one is the cell we are allowed to change color. \n\n**End of Q & A**\n\n----\n\nStarting from the given cell, check if any of the 8 directions has a good line.\n\nFor each direction:\nCheck if ... | 14 | You are given a **0-indexed** `8 x 8` grid `board`, where `board[r][c]` represents the cell `(r, c)` on a game board. On the board, free cells are represented by `'.'`, white cells are represented by `'W'`, and black cells are represented by `'B'`.
Each move in this game consists of choosing a free cell and changing i... | null |
[Python3] check 8 directions | check-if-move-is-legal | 0 | 1 | \n```\nclass Solution:\n def checkMove(self, board: List[List[str]], rMove: int, cMove: int, color: str) -> bool:\n for di, dj in (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1): \n i, j = rMove+di, cMove+dj\n step = 0\n while 0 <= i < 8 and 0 <= j < 8: \n... | 8 | You are given a **0-indexed** `8 x 8` grid `board`, where `board[r][c]` represents the cell `(r, c)` on a game board. On the board, free cells are represented by `'.'`, white cells are represented by `'W'`, and black cells are represented by `'B'`.
Each move in this game consists of choosing a free cell and changing i... | null |
Recursive Solution | check-if-move-is-legal | 0 | 1 | # Code\n```\nclass Solution:\n def checkMove(self, board: List[List[str]], rMove: int, cMove: int, color: str) -> bool:\n nrows = len(board)\n ncols = len(board[0])\n directions = [[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]]\n \n def dfs(r,c,d,endpoint,length):\n ... | 0 | You are given a **0-indexed** `8 x 8` grid `board`, where `board[r][c]` represents the cell `(r, c)` on a game board. On the board, free cells are represented by `'.'`, white cells are represented by `'W'`, and black cells are represented by `'B'`.
Each move in this game consists of choosing a free cell and changing i... | null |
[Python3] dp | minimum-total-space-wasted-with-k-resizing-operations | 0 | 1 | \n```\nclass Solution:\n def minSpaceWastedKResizing(self, nums: List[int], k: int) -> int:\n \n @cache\n def fn(i, k): \n """Return min waste from i with k ops."""\n if i == len(nums): return 0\n if k < 0: return inf \n ans = inf\n rmx = rs... | 14 | You are currently designing a dynamic array. You are given a **0-indexed** integer array `nums`, where `nums[i]` is the number of elements that will be in the array at time `i`. In addition, you are given an integer `k`, the **maximum** number of times you can **resize** the array (to **any** size).
The size of the ar... | The grid is at a maximum 100 x 100, so it is clever to assume that the robot's initial cell is grid[101][101] Run a DFS from the robot's position to make sure that you can reach the target, otherwise you should return -1. Now that you are sure you can reach the target and that you know the grid, run Dijkstra to find th... |
✔ Python3 Solution | DP | Clean & Concise | minimum-total-space-wasted-with-k-resizing-operations | 0 | 1 | # Complexity\n- Time complexity: $$O(K * N ^ 2)$$\n- Space complexity: $$O(N)$$\n\n# Code\n```Python\nclass Solution:\n def minSpaceWastedKResizing(self, A, K):\n N = len(A)\n dp = [0] + [float(\'inf\')] * N\n for k in range(K + 1):\n for i in range(N - 1, k - 1, -1):\n ... | 2 | You are currently designing a dynamic array. You are given a **0-indexed** integer array `nums`, where `nums[i]` is the number of elements that will be in the array at time `i`. In addition, you are given an integer `k`, the **maximum** number of times you can **resize** the array (to **any** size).
The size of the ar... | The grid is at a maximum 100 x 100, so it is clever to assume that the robot's initial cell is grid[101][101] Run a DFS from the robot's position to make sure that you can reach the target, otherwise you should return -1. Now that you are sure you can reach the target and that you know the grid, run Dijkstra to find th... |
Python DP Top Down Solution | minimum-total-space-wasted-with-k-resizing-operations | 0 | 1 | ```\nclass Solution:\n def minSpaceWastedKResizing(self, nums: List[int], k: int) -> int:\n memo = {}\n\n def f(index,k):\n if (index,k) in memo: return memo[(index,k)]\n if index >= len(nums): return 0\n \n res = float("inf")\n if k > 0:\n ... | 0 | You are currently designing a dynamic array. You are given a **0-indexed** integer array `nums`, where `nums[i]` is the number of elements that will be in the array at time `i`. In addition, you are given an integer `k`, the **maximum** number of times you can **resize** the array (to **any** size).
The size of the ar... | The grid is at a maximum 100 x 100, so it is clever to assume that the robot's initial cell is grid[101][101] Run a DFS from the robot's position to make sure that you can reach the target, otherwise you should return -1. Now that you are sure you can reach the target and that you know the grid, run Dijkstra to find th... |
Python DP Faster than 86% | minimum-total-space-wasted-with-k-resizing-operations | 0 | 1 | wasted[i][j] means the wasted space for nums[i] to nums[j].\ndp[k][i] means the minimum wasted space for nums[0] to nums[i] with k resize operations.\nThe subproblem can be represent as \n\ndp[k][i] = min(dp[k-1][l-1] + wasted[l][i]), where l is from k to i\n\n\n```\nclass Solution:\n def minSpaceWastedKResizing(sel... | 2 | You are currently designing a dynamic array. You are given a **0-indexed** integer array `nums`, where `nums[i]` is the number of elements that will be in the array at time `i`. In addition, you are given an integer `k`, the **maximum** number of times you can **resize** the array (to **any** size).
The size of the ar... | The grid is at a maximum 100 x 100, so it is clever to assume that the robot's initial cell is grid[101][101] Run a DFS from the robot's position to make sure that you can reach the target, otherwise you should return -1. Now that you are sure you can reach the target and that you know the grid, run Dijkstra to find th... |
[python3] DP with memoization, beat 100% python submissions | minimum-total-space-wasted-with-k-resizing-operations | 0 | 1 | ```\nclass Solution:\n def minSpaceWastedKResizing(self, A: List[int], K: int) -> int:\n def waste(i, j, h):\n sumI = sums[i-1] if i > 0 else 0\n return (j-i+1)*h - sums[j] + sumI\n \n def dp(i, k):\n if i <= k:\n return 0\n if k < 0:\n ... | 1 | You are currently designing a dynamic array. You are given a **0-indexed** integer array `nums`, where `nums[i]` is the number of elements that will be in the array at time `i`. In addition, you are given an integer `k`, the **maximum** number of times you can **resize** the array (to **any** size).
The size of the ar... | The grid is at a maximum 100 x 100, so it is clever to assume that the robot's initial cell is grid[101][101] Run a DFS from the robot's position to make sure that you can reach the target, otherwise you should return -1. Now that you are sure you can reach the target and that you know the grid, run Dijkstra to find th... |
[Python3] Manacher | maximum-product-of-the-length-of-two-palindromic-substrings | 0 | 1 | \n```\nclass Solution:\n def maxProduct(self, s: str) -> int:\n n = len(s)\n \n # Manacher\'s algo\n hlen = [0]*n # half-length\n center = right = 0 \n for i in range(n): \n if i < right: hlen[i] = min(right - i, hlen[2*center - i])\n while 0 <= i-1-hle... | 4 | You are given a **0-indexed** string `s` and are tasked with finding two **non-intersecting palindromic** substrings of **odd** length such that the product of their lengths is maximized.
More formally, you want to choose four integers `i`, `j`, `k`, `l` such that `0 <= i <= j < k <= l < s.length` and both the substri... | Iterate over the string and mark each character as found (using a boolean array, bitmask, or any other similar way). Check if the number of found characters equals the alphabet length. |
Python (Simple Manacher's algorithm) | maximum-product-of-the-length-of-two-palindromic-substrings | 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 **0-indexed** string `s` and are tasked with finding two **non-intersecting palindromic** substrings of **odd** length such that the product of their lengths is maximized.
More formally, you want to choose four integers `i`, `j`, `k`, `l` such that `0 <= i <= j < k <= l < s.length` and both the substri... | Iterate over the string and mark each character as found (using a boolean array, bitmask, or any other similar way). Check if the number of found characters equals the alphabet length. |
Premium Limited Explained Solution | maximum-product-of-the-length-of-two-palindromic-substrings | 1 | 1 | \n```\nclass Solution\n{\npublic:\n long long maxProduct(string s)\n {\n\n int n = s.size();\n vector<int> d1 = vector<int>(s.size(), 0);\n for (int i = 0, l = 0, r = -1; i < n; i++)\n {\n int k = (i > r) ? 1 : min(d1[l + r - i], r - i + 1);\n while (0 <= i - k &&... | 0 | You are given a **0-indexed** string `s` and are tasked with finding two **non-intersecting palindromic** substrings of **odd** length such that the product of their lengths is maximized.
More formally, you want to choose four integers `i`, `j`, `k`, `l` such that `0 <= i <= j < k <= l < s.length` and both the substri... | Iterate over the string and mark each character as found (using a boolean array, bitmask, or any other similar way). Check if the number of found characters equals the alphabet length. |
[Python3] move along s | check-if-string-is-a-prefix-of-array | 0 | 1 | \n```\nclass Solution:\n def isPrefixString(self, s: str, words: List[str]) -> bool:\n i = 0\n for word in words: \n if s[i:i+len(word)] != word: return False \n i += len(word)\n if i == len(s): return True \n return False \n```\n\nThe solutions for weekly 255 ca... | 24 | Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`.
A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive** `k` no larger than `words.length`.
Return `true` _if_ `s` _is a **prefi... | It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first. |
python3 code | check-if-string-is-a-prefix-of-array | 0 | 1 | # Code\n```\nclass Solution:\n def isPrefixString(self, s: str, words):\n subresult = [\'\'.join(words[:i+1]) for i in range(len(words))]\n for substr in subresult:\n if substr == s: return True\n return False\n```\n\n:\n return s in accumulate(words)\n``` | 5 | Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`.
A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive** `k` no larger than `words.length`.
Return `true` _if_ `s` _is a **prefi... | It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first. |
Python Easy | check-if-string-is-a-prefix-of-array | 0 | 1 | ```\nclass Solution:\n def isPrefixString(self, s: str, words: List[str]) -> bool:\n \n a = \'\'\n \n for i in words:\n \n a += i\n \n if a == s:\n return True\n if not s.startswith(a):\n break\n ... | 11 | Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`.
A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive** `k` no larger than `words.length`.
Return `true` _if_ `s` _is a **prefi... | It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first. |
Python solution for beginners by beginner. | check-if-string-is-a-prefix-of-array | 0 | 1 | \nRuntime: 36 ms, faster than 91.08% of Python3 online submissions for Check If String Is a Prefix of Array.\nMemory Usage: 13.8 MB, less than 97.53% of Python3 online submissions for Check If String Is a Prefix of Array.\n\n```\nclass Solution:\n def isPrefixString(self, s: str, words: List[str]) -> bool:\n ... | 3 | Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`.
A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive** `k` no larger than `words.length`.
Return `true` _if_ `s` _is a **prefi... | It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first. |
Python easy to understand | check-if-string-is-a-prefix-of-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`.
A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive** `k` no larger than `words.length`.
Return `true` _if_ `s` _is a **prefi... | It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first. |
[ Python3] Simple Brute Force - Beginner | check-if-string-is-a-prefix-of-array | 0 | 1 | **Brute Force Solution**\n```\nclass Solution:\n def isPrefixString(self, s: str, words: List[str]) -> bool:\n #Initialize empty string\n\t\tpr = \'\'\n\t\t#Store the length of string\n l = len(s)\n for i in words:\n\t\t\t#keep concatenating the elements in words to pr and check if it is equal t... | 0 | Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`.
A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive** `k` no larger than `words.length`.
Return `true` _if_ `s` _is a **prefi... | It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first. |
Python | check-if-string-is-a-prefix-of-array | 0 | 1 | # 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(n)$$ -->\n O(1)\n# Code\n```\nclass Solution:\n def isPrefixString(self, s: str, words: List[str]) -> bool:\n word = \'\'\n\n for i in... | 0 | Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`.
A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive** `k` no larger than `words.length`.
Return `true` _if_ `s` _is a **prefi... | It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first. |
Python - Priority Queue - Beats 90% | remove-stones-to-minimize-the-total | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nUse a max heap to retrieve the max element every time. We will then run k operations until we have our minimum sum. We must push a negative value because heapq in python is default to minheap.\n# Code\n```\nclass Solution:\n def minStoneSum(self, p... | 4 | You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the ... | To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks |
[Python] 90% -- unusual -- use dict and iterate from max stones | remove-stones-to-minimize-the-total | 0 | 1 | # Summary \nThe solution is fast due to the use of a dictionary that uses hashing and due to the fact that we do not move the piles in any way (we just change the number of piles in the dict). But we use a lot of memory for this.\n\n\n\u2764\uFE0F **Please upvote if you liked this unusual approach**\n\n# Approach\n<!--... | 3 | You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the ... | To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks |
Max Heap Solution | remove-stones-to-minimize-the-total | 0 | 1 | ```\nimport heapq\n\nclass Solution:\n def minStoneSum(self, piles: List[int], k: int) -> int:\n maxHeap = []\n \n for i in range(len(piles)):\n heapq.heappush(maxHeap, -piles[i])\n\n i = k\n while i > 0:\n temp = heapq.heappop(maxHeap)\n j = temp//... | 3 | You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the ... | To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks |
Python | O(n + max) w/o Heap | remove-stones-to-minimize-the-total | 0 | 1 | # Intuition\n\nSince the piles are relatively small, there are more efficient ways to maintain a priority queue.\n\n# Approach\n\nUse a frequency table to handle duplicate pile sizes: `cnt[size]` is the number of piles with given `size`. \n\nAfter building the table, loop from largest to smallest pile size and batch pr... | 2 | You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the ... | To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks |
[Python] Hash table, beats 100% | remove-stones-to-minimize-the-total | 0 | 1 | # Description\nHere\'s something a bit different from the typical heap solution.\n\nObserve that the *entries* in the input actually have an upper bound that is *below* the maximum input length, which makes hash table an efficient choice of data structure. The keys are integers, so we can use an array as the hash table... | 2 | You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the ... | To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks |
Python3 Heap | remove-stones-to-minimize-the-total | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn each iteration, we need to \n1. pop the maximum elements in piles\n2. do the operation \n3. put the new element back to piles\n\nWe could simply implement it by sort piles, get the maximum, do the operation and put it back. However, it... | 1 | You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the ... | To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks |
Easy Python Solution using maxHeap | remove-stones-to-minimize-the-total | 0 | 1 | # Intuition\nEach operation involves selecting a pile of stones with the maximum number of stones, removing half of the stones, and putting the remaining stones back into the pile. The code then returns the maximum number of stones that can be left in the piles after all operations are performed.\n\n# Approach\nThe cod... | 1 | You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the ... | To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks |
Max heap|| with intuition and approach || with picture explanation || Ceil not Floor | remove-stones-to-minimize-the-total | 0 | 1 | # Approach\n- We have been given a pile of stones and from these we have to remove \nceil(piles[i]/2) stones\n- we can perform above operattion of removing stone on the same pile more than once\n- k -> it is the no of times you have to perform above operation\n- And we need to return minimum no of stones left after per... | 1 | You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the ... | To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks |
Python3 | 1400 ms (100% faster code) | O(max(n*ln(n), k)) | remove-stones-to-minimize-the-total | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst of all, sort given array in non-decreasing order. Time complexity $$O(n * ln(n))$$. \nThen we do the following steps:\n- we find the maximum value between the last element in the array and the first element in the queue\n- pop this ... | 1 | You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the ... | To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks |
python3, sortedcontainers.SortedList() | remove-stones-to-minimize-the-total | 0 | 1 | https://leetcode.com/submissions/detail/866817274/\nRuntime: 3083 ms \nMemory Usage: 29 MB \n```\nfrom sortedcontainers import SortedList\nclass Solution:\n def minStoneSum(self, piles: List[int], k: int) -> int:\n l = SortedList()\n l.update(piles)\n remained = sum(piles)\n for _ in ra... | 1 | You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the ... | To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks |
Python | Max Heap | remove-stones-to-minimize-the-total | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nNeed to greedily figureout the maximum element of the pile.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse a max heap to store the piles. Pop the heap, modify the pile and then push it back in the heap.\n\n# C... | 1 | You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the ... | To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks |
Easy python solution using min heap :) 🔥 | remove-stones-to-minimize-the-total | 0 | 1 | # Intuition\nwe need to reduce the maximum element in array so we need to keep track of max elememt :) so heap comes in our way.\n\n# Approach\nI used heapq to heapify the given array by multiplying each value by -1 to get a max heap :)\n\n# Complexity\n- Time complexity: O(n + log(n))\n\n- Space complexity: O(n)\n<!--... | 1 | You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the ... | To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks |
Beginner-friendly || Simple stack-simulation in Python3 | minimum-number-of-swaps-to-make-the-string-balanced | 0 | 1 | # Intuition\nLets clarify the description:\n- our task is to validate sequence of **brackets**, that consists **exactly** of pairs `[` and `]` (50% / 50%)\n- the final answer will represent the **count** of swaps that\'re needed to perform in order to make a sequence **valid**\n \n```py\n# Example 1\nseq = \'[[]]\'\n# ... | 1 | You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`.
A string is called **balanced** if and only if:
* It is the empty string, or
* It can be written as `AB`, where both `A` and `B` are **balanced** s... | Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[... |
O(n) time with O(1) space - Counting problem | minimum-number-of-swaps-to-make-the-string-balanced | 0 | 1 | # Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution:\n def minSwaps(self, s: str) -> int:\n\n\n # stack = []\n count = 0\n res = 0\n ... | 1 | You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`.
A string is called **balanced** if and only if:
* It is the empty string, or
* It can be written as `AB`, where both `A` and `B` are **balanced** s... | Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[... |
[Python 3] Stack - Simple | minimum-number-of-swaps-to-make-the-string-balanced | 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... | 8 | You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`.
A string is called **balanced** if and only if:
* It is the empty string, or
* It can be written as `AB`, where both `A` and `B` are **balanced** s... | Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[... |
[Java/Python 3] Space O(1) time O(n) codes w/ brief explanation. | minimum-number-of-swaps-to-make-the-string-balanced | 1 | 1 | Traverse the input `s`, remove all matched `[]`\'s. Since the number of `[`\'s and `]`\'s are same, the remaining must be `]]]...[[[`. Otherwise, **if left half had any `[`, there would be at least a matched `[]` among them.**\n\n1. For every `2` pairs of square brackets, a swap will make them matched;\n2. If only `1` ... | 47 | You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`.
A string is called **balanced** if and only if:
* It is the empty string, or
* It can be written as `AB`, where both `A` and `B` are **balanced** s... | Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[... |
Two Pointers | minimum-number-of-swaps-to-make-the-string-balanced | 0 | 1 | We go left to right (`i`), and track open and closed brackets in `bal`. When `bal` goes negative, we have an orphan `]`. \n\nTo balance it out, we need to find an orphaned `[` and swap those two. So, we go right-to-left (`j`), and we can search for the orphaned `[`. \n\nWhy is this strategy optimal? Because we have to ... | 23 | You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`.
A string is called **balanced** if and only if:
* It is the empty string, or
* It can be written as `AB`, where both `A` and `B` are **balanced** s... | Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[... |
✔ Python3 Solution | Clean & Concise | minimum-number-of-swaps-to-make-the-string-balanced | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def minSwaps(self, s):\n cur, ans = 0, 0\n for i in s:\n if i == \']\' and cur == 0: ans += 1\n if i == \'[\' or cur == 0: cur += 1\n else: cur -= 1\n return... | 2 | You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`.
A string is called **balanced** if and only if:
* It is the empty string, or
* It can be written as `AB`, where both `A` and `B` are **balanced** s... | Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[... |
Easy and Intuitive Python Solution With Images and Walkthrough | minimum-number-of-swaps-to-make-the-string-balanced | 0 | 1 | ## Hi guys, I hope my post can help you in understanding this problem. ##\n\n### First, we need to understand what is the "**balanced**" scenario. There are 3 types of balanced scenario as shown below: ###\n<img src = "https://assets.leetcode.com/users/images/cd21075c-57a8-46b0-bd0e-911d7e13e3b1_1649990481.5305083.png"... | 18 | You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`.
A string is called **balanced** if and only if:
* It is the empty string, or
* It can be written as `AB`, where both `A` and `B` are **balanced** s... | Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[... |
pyton easy soution understadble | minimum-number-of-swaps-to-make-the-string-balanced | 0 | 1 | * 1. class Solution:\n* def minSwaps(self, s: str) -> int:\n* c=0\n* for i in s:\n* if i=="[":\n* c=c+1\n* elif c>0:\n* c=c-1\n* return (c+1)//2 | 1 | You are given a **0-indexed** string `s` of **even** length `n`. The string consists of **exactly** `n / 2` opening brackets `'['` and `n / 2` closing brackets `']'`.
A string is called **balanced** if and only if:
* It is the empty string, or
* It can be written as `AB`, where both `A` and `B` are **balanced** s... | Think about (a&b) ^ (a&c). Can you simplify this expression? It is equal to a&(b^c). Then, (arr1[i]&arr2[0])^(arr1[i]&arr2[1]).. = arr1[i]&(arr2[0]^arr2[1]^arr[2]...). Let arr2XorSum = (arr2[0]^arr2[1]^arr2[2]...), arr1XorSum = (arr1[0]^arr1[1]^arr1[2]...) so the final answer is (arr2XorSum&arr1[0]) ^ (arr2XorSum&arr1[... |
Python | Binary Search | Easy to Understand | Beats 99% | find-the-longest-valid-obstacle-course-at-each-position | 0 | 1 | Simple Upper Bound and Binary Search\n\n```\nclass Solution:\n def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]:\n stack,ans=[],[]\n \n for i in obstacles:\n br=bisect_right(stack,i)\n if br==len(stack):\n stack.append(i)\n ... | 9 | You want to build some obstacle courses. You are given a **0-indexed** integer array `obstacles` of length `n`, where `obstacles[i]` describes the height of the `ith` obstacle.
For every index `i` between `0` and `n - 1` (**inclusive**), find the length of the **longest obstacle course** in `obstacles` such that:
* ... | null |
Binary search easy solution | find-the-longest-valid-obstacle-course-at-each-position | 0 | 1 | # Code\n```\nclass Solution:\n def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]:\n\n def bisearch(lis, height):\n l, r = 0, len(lis)\n while l < r:\n m = (l + r) // 2\n if height < lis[m]:\n r = m\n ... | 1 | You want to build some obstacle courses. You are given a **0-indexed** integer array `obstacles` of length `n`, where `obstacles[i]` describes the height of the `ith` obstacle.
For every index `i` between `0` and `n - 1` (**inclusive**), find the length of the **longest obstacle course** in `obstacles` such that:
* ... | null |
python 3 - Binary search | find-the-longest-valid-obstacle-course-at-each-position | 0 | 1 | # Intuition\n(this question becomes a piece of cake if you use python :P)\n\nTo do this question, you must know the technique in solving 300. Longest Increasing Subsequence. This question is an advance version of Q300.\n\nThis question ask you to find the longest increasing subseqence for each i.\n\nYou can\'t use Sort... | 1 | You want to build some obstacle courses. You are given a **0-indexed** integer array `obstacles` of length `n`, where `obstacles[i]` describes the height of the `ith` obstacle.
For every index `i` between `0` and `n - 1` (**inclusive**), find the length of the **longest obstacle course** in `obstacles` such that:
* ... | null |
Patience Sort - Same as Longest Increasing Subsequence | find-the-longest-valid-obstacle-course-at-each-position | 0 | 1 | \n# Code\n```\nclass Solution:\n def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]:\n arr, res = [], [0] * len(obstacles)\n for i, x in enumerate(obstacles):\n k = bisect_right(arr, x)\n if k == len(arr): arr.append(x)\n else: arr[k] = x\n... | 1 | You want to build some obstacle courses. You are given a **0-indexed** integer array `obstacles` of length `n`, where `obstacles[i]` describes the height of the `ith` obstacle.
For every index `i` between `0` and `n - 1` (**inclusive**), find the length of the **longest obstacle course** in `obstacles` such that:
* ... | null |
python3 Solution | find-the-longest-valid-obstacle-course-at-each-position | 0 | 1 | \n```\nclass Solution:\n def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]:\n mono=[]\n ans=[]\n for obstacl in obstacles:\n i=bisect.bisect(mono,obstacl)\n ans.append(i+1)\n if i==len(mono):\n mono.append(0)\n\n ... | 1 | You want to build some obstacle courses. You are given a **0-indexed** integer array `obstacles` of length `n`, where `obstacles[i]` describes the height of the `ith` obstacle.
For every index `i` between `0` and `n - 1` (**inclusive**), find the length of the **longest obstacle course** in `obstacles` such that:
* ... | null |
Easy Understand | Simple Method | Binary Search + Stack | Java | Python | C++✅ | find-the-longest-valid-obstacle-course-at-each-position | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEvery time a number is traversed, if:\n- If the current number is greater than or equal to the number on the top of the stack, it will be directly pushed onto the stack\n- If the current number is less than the number on the top of the st... | 27 | You want to build some obstacle courses. You are given a **0-indexed** integer array `obstacles` of length `n`, where `obstacles[i]` describes the height of the `ith` obstacle.
For every index `i` between `0` and `n - 1` (**inclusive**), find the length of the **longest obstacle course** in `obstacles` such that:
* ... | null |
python3 solution beats 98.48% 🚀🚀🔥 || quibler7 | find-the-longest-valid-obstacle-course-at-each-position | 0 | 1 | # Code\n```\nclass Solution:\n def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]:\n n = len(obstacles)\n res = n*[1]\n v = []\n for i in range(n):\n tr = bisect_right(v, obstacles[i])\n if tr == len(v): v.append(obstacles[i])\n ... | 1 | You want to build some obstacle courses. You are given a **0-indexed** integer array `obstacles` of length `n`, where `obstacles[i]` describes the height of the `ith` obstacle.
For every index `i` between `0` and `n - 1` (**inclusive**), find the length of the **longest obstacle course** in `obstacles` such that:
* ... | null |
[Python3] 1-line | number-of-strings-that-appear-as-substrings-in-word | 0 | 1 | \n```\nclass Solution:\n def numOfStrings(self, patterns: List[str], word: str) -> int:\n return sum(x in word for x in patterns)\n```\n\nYou can find the solutions to weekly 254 in this [repo](https://github.com/gaosanyong/leetcode/commit/dcc452fea7d159bd4fae8318c14d546f17783894). | 23 | Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** patterns = \[ "a ", "abc ", "bc ", "d "\], word = "abc "
**Output:**... | Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring. |
C++ / Python (1 line) simple solution | number-of-strings-that-appear-as-substrings-in-word | 0 | 1 | **C++ :**\n\n```\nint numOfStrings(vector<string>& patterns, string word) {\n int counter = 0;\n \n for(auto p: patterns)\n if(word.find(p) != std::string::npos)\n ++counter;\n \n return counter;\n }\n```\n\n**Python :**\n\n```\ndef numOfStrings(self, patt... | 16 | Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** patterns = \[ "a ", "abc ", "bc ", "d "\], word = "abc "
**Output:**... | Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring. |
smallest solution in python by smarthood | number-of-strings-that-appear-as-substrings-in-word | 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)$$ --... | 2 | Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** patterns = \[ "a ", "abc ", "bc ", "d "\], word = "abc "
**Output:**... | Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring. |
Python one-liner | number-of-strings-that-appear-as-substrings-in-word | 0 | 1 | ```\nclass Solution:\n def numOfStrings(self, patterns: List[str], word: str) -> int:\n return len([pattern for pattern in patterns if pattern in word])\n``` | 1 | Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** patterns = \[ "a ", "abc ", "bc ", "d "\], word = "abc "
**Output:**... | Start from each 'a' and find the longest beautiful substring starting at that index. Based on the current character decide if you should include the next character in the beautiful substring. |
Swap & One Loop || Python 3 | array-with-elements-not-equal-to-average-of-neighbors | 0 | 1 | # Intuition\nI found it a very mathematical based question rather than using an algorithm for this. Though there are various sorting algorithm but you can solve it using normal swaps.\nkeep your window of size 3 and check is the window is sorted in any manner (reverse included) it is so then swap any two elements and m... | 1 | You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1... | Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right. |
python3 unknown approach ??? o(n) | array-with-elements-not-equal-to-average-of-neighbors | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def rearrangeArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n res = []\n i= 0 \n j=len(nums)-1\n while i<j:\n res.append(nums[i])\n res.append(nums[j])\n i+=1\n j-=1\n if len(res) != len... | 1 | You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1... | Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right. |
Clean and simple O(N) and O(1) python solution | array-with-elements-not-equal-to-average-of-neighbors | 0 | 1 | \n# Code\n```\nclass Solution:\n def rearrangeArray(self, nums: List[int]) -> List[int]:\n #Time - O(N) and space - O(1)\n # This is in place replacement\n # Step 1: Even place i has to be less than i-1\n # Step 2: odd place i has to be greater than i-1\n # Step 1 and 2 can be inte... | 1 | You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1... | Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right. |
PYTHON EASY SOLUTION | array-with-elements-not-equal-to-average-of-neighbors | 0 | 1 | The only way the average of the neighbors can give us the number is if one of them is greater and the other is smaller than the middle number.\n\nTo make the number different from the average of its neighbors, we just have to first sort the array and then take one number from the start then from the end. If we do the s... | 1 | You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1... | Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right. |
Beats 99% - Easy to Understand - Wiggle Sort! | array-with-elements-not-equal-to-average-of-neighbors | 0 | 1 | # Intuition\n- Exact solution to wiggle sort\n- If two neighbours are both higher -> middle element can\'t be average\n- If two neighbours are both lower -> middle element can\'t be average\n\n# Code\n```\nclass Solution:\n def rearrangeArray(self, nums: List[int]) -> List[int]:\n def swap(i,j):\n ... | 0 | You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1... | Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right. |
Unproven theory but beats 90%+ in cpu and memory | array-with-elements-not-equal-to-average-of-neighbors | 0 | 1 | # Intuition\nReduce the chances that your resultin array will fail by rearranging the numers as follows:\n1. sort `nums`\n2. take the array of every other element from the sorted `nums` and...\n3. reverse that sub-array\n4. put it back in place\n5. The center element is now still your most likely \'problem\' element si... | 0 | You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1... | Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right. |
Sorted - Interleaving - O(nlogn) | array-with-elements-not-equal-to-average-of-neighbors | 0 | 1 | # Complexity\n```\n- Time complexity: O(nlogn)\n- Space complexity: O(n)\n```\n# Code\n```python\nclass Solution:\n def rearrangeArray(self, A: List[int]) -> List[int]:\n B = sorted(A); A[1::2], A[::2] = B[:len(B) // 2], B[len(B) // 2:]\n return A\n``` | 0 | You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1... | Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right. |
Python easy sol.. | array-with-elements-not-equal-to-average-of-neighbors | 0 | 1 | \n# Code\n```\nclass Solution:\n def rearrangeArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n print(nums)\n res=[]\n f,r=0,len(nums)-1\n while f<r:\n res.append(nums[f])\n res.append(nums[r])\n f+=1\n r-=1\n if f==r:\n ... | 0 | You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1... | Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right. |
Python Two Pointers with Explanation | array-with-elements-not-equal-to-average-of-neighbors | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def rearrangeArray(self, nums: List[int]) -> List[int]:\n # Time --> O(n)\n # Space --> O(1) as output as is not counted\n\n # Logic:\n # First, sort the list, then use two-pointer concept, keep two pointers, left and right.\n # left = 0 and right... | 0 | You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1... | Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right. |
[Python] One-liner solution with mathematical proof and explanation | minimum-non-zero-product-of-the-array-elements | 0 | 1 | To calculate the minimum non-zero product we always have to change the value such as it will provide the minimum multiplication value -\n\ni.e \nn = 3\n1 - 001\n2 - 010\n3 - 011\n4 - 100\n5 - 101\n6 - 110\n7 - 111\n\nHere we convert all the value **i** to **1** and **pow(2, n)-i-1** to **pow(2, n)-2** *(where i<pow(2... | 6 | You are given a positive integer `p`. Consider an array `nums` (**1-indexed**) that consists of the integers in the **inclusive** range `[1, 2p - 1]` in their binary representations. You are allowed to do the following operation **any** number of times:
* Choose two elements `x` and `y` from `nums`.
* Choose a bit... | We can see that the problem can be represented as a directed graph with an edge from each boy to the girl he invited. We need to choose a set of edges such that no to source points in the graph (i.e., boys) have an edge with the same endpoint (i.e., the same girl). The problem is maximum bipartite matching in the graph... |
[Python3] 2-line | minimum-non-zero-product-of-the-array-elements | 0 | 1 | \n```\nclass Solution:\n def minNonZeroProduct(self, p: int) -> int:\n x = (1 << p) - 1\n return pow(x-1, (x-1)//2, 1_000_000_007) * x % 1_000_000_007\n```\n\nYou can find the solutions to weekly 256 in this [repo](https://github.com/gaosanyong/leetcode/commit/dcc452fea7d159bd4fae8318c14d546f17783894). | 6 | You are given a positive integer `p`. Consider an array `nums` (**1-indexed**) that consists of the integers in the **inclusive** range `[1, 2p - 1]` in their binary representations. You are allowed to do the following operation **any** number of times:
* Choose two elements `x` and `y` from `nums`.
* Choose a bit... | We can see that the problem can be represented as a directed graph with an edge from each boy to the girl he invited. We need to choose a set of edges such that no to source points in the graph (i.e., boys) have an edge with the same endpoint (i.e., the same girl). The problem is maximum bipartite matching in the graph... |
Python solution: get as many 1 as possible | minimum-non-zero-product-of-the-array-elements | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs swaps cannot change total number of 1 and 0s in a bit, and the question asks for minimum NONZERO product, so it\'s all about getting as many 1 in the final state as possible. ($$1 = 0001, 14 = 1110, 2 = 0010, 13 = 1101$$, $$1 \\times 1... | 0 | You are given a positive integer `p`. Consider an array `nums` (**1-indexed**) that consists of the integers in the **inclusive** range `[1, 2p - 1]` in their binary representations. You are allowed to do the following operation **any** number of times:
* Choose two elements `x` and `y` from `nums`.
* Choose a bit... | We can see that the problem can be represented as a directed graph with an edge from each boy to the girl he invited. We need to choose a set of edges such that no to source points in the graph (i.e., boys) have an edge with the same endpoint (i.e., the same girl). The problem is maximum bipartite matching in the graph... |
[Python] | minimum-non-zero-product-of-the-array-elements | 0 | 1 | # Intuition\nYou have to match ones with largest possible numbers:\nSo we will have \n`000...01`\n`111...10`\ncoming in pairs.\nAnd there will be one remaining\n`111...11`\nYou have to multiply them all. For this is best to implement pow(x,y) function which calculates powers quickly.\n\n# Speed up\nSince there are only... | 0 | You are given a positive integer `p`. Consider an array `nums` (**1-indexed**) that consists of the integers in the **inclusive** range `[1, 2p - 1]` in their binary representations. You are allowed to do the following operation **any** number of times:
* Choose two elements `x` and `y` from `nums`.
* Choose a bit... | We can see that the problem can be represented as a directed graph with an edge from each boy to the girl he invited. We need to choose a set of edges such that no to source points in the graph (i.e., boys) have an edge with the same endpoint (i.e., the same girl). The problem is maximum bipartite matching in the graph... |
Maximise & Minimise Patterns | Very Descriptive | Greedy & Math | minimum-non-zero-product-of-the-array-elements | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMathematics has sometimes been called a science of patterns (Resnik, 1981). In this particular problem you do not dare to do the `brute-force`(change all numbers to binary form and try to change the numbers in the binary representation bi... | 0 | You are given a positive integer `p`. Consider an array `nums` (**1-indexed**) that consists of the integers in the **inclusive** range `[1, 2p - 1]` in their binary representations. You are allowed to do the following operation **any** number of times:
* Choose two elements `x` and `y` from `nums`.
* Choose a bit... | We can see that the problem can be represented as a directed graph with an edge from each boy to the girl he invited. We need to choose a set of edges such that no to source points in the graph (i.e., boys) have an edge with the same endpoint (i.e., the same girl). The problem is maximum bipartite matching in the graph... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.