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
simple
check-if-all-the-integers-in-a-range-are-covered
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 `ranges` and two integers `left` and `right`. Each `ranges[i] = [starti, endi]` represents an **inclusive** interval between `starti` and `endi`. Return `true` _if each integer in the inclusive range_ `[left, right]` _is covered by **at least one** interval in_ `ranges`. Return `false`...
Think about dynamic programming Define an array dp[nums.length][2], where dp[i][0] is the max subarray sum including nums[i] and without squaring any element. dp[i][1] is the max subarray sum including nums[i] and having only one element squared.
🐍🐍🐍 One line solution 🐍🐍🐍
check-if-all-the-integers-in-a-range-are-covered
0
1
# Code\n```\nclass Solution:\n def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:\n return len(set([i for i in range(left, right +1)]) - set([i for x in ranges for i in range(x[0],x[1]+1)])) == 0\n```
0
You are given a 2D integer array `ranges` and two integers `left` and `right`. Each `ranges[i] = [starti, endi]` represents an **inclusive** interval between `starti` and `endi`. Return `true` _if each integer in the inclusive range_ `[left, right]` _is covered by **at least one** interval in_ `ranges`. Return `false`...
Think about dynamic programming Define an array dp[nums.length][2], where dp[i][0] is the max subarray sum including nums[i] and without squaring any element. dp[i][1] is the max subarray sum including nums[i] and having only one element squared.
python solution
check-if-all-the-integers-in-a-range-are-covered
0
1
\n\n# Complexity\n- Time complexity:\nO(N*M)\n\n\n# Code\n```\nclass Solution:\n def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:\n range_list = []\n for i in range(len(ranges)):\n for j in range(ranges[i][0], ranges[i][1] + 1):\n range_list.append(...
0
You are given a 2D integer array `ranges` and two integers `left` and `right`. Each `ranges[i] = [starti, endi]` represents an **inclusive** interval between `starti` and `endi`. Return `true` _if each integer in the inclusive range_ `[left, right]` _is covered by **at least one** interval in_ `ranges`. Return `false`...
Think about dynamic programming Define an array dp[nums.length][2], where dp[i][0] is the max subarray sum including nums[i] and without squaring any element. dp[i][1] is the max subarray sum including nums[i] and having only one element squared.
Easy Solution | Java | Python
find-the-student-that-will-replace-the-chalk
1
1
# Python\n```\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n sums = sum(chalk)\n div = k // sums\n k = k - (sums * div)\n for i in range(len(chalk)):\n if chalk[i] <= k:\n k -= chalk[i]\n else:\n return i\...
2
There are `n` students in a class numbered from `0` to `n - 1`. The teacher will give each student a problem starting with the student number `0`, then the student number `1`, and so on until the teacher reaches the student number `n - 1`. After that, the teacher will restart the process, starting with the student numb...
Use two pointers, one pointer for each string. Alternately choose the character from each pointer, and move the pointer upwards.
[Python3] Prefix Sum + Binary Search - Easy to Understand
find-the-student-that-will-replace-the-chalk
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 + logn) ~ O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space c...
2
There are `n` students in a class numbered from `0` to `n - 1`. The teacher will give each student a problem starting with the student number `0`, then the student number `1`, and so on until the teacher reaches the student number `n - 1`. After that, the teacher will restart the process, starting with the student numb...
Use two pointers, one pointer for each string. Alternately choose the character from each pointer, and move the pointer upwards.
Python || Prefix Sum and Binary Search || O(n) time O(n) space
find-the-student-that-will-replace-the-chalk
0
1
```\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n prefix_sum = [0 for i in range(len(chalk))]\n prefix_sum[0] = chalk[0]\n for i in range(1,len(chalk)):\n prefix_sum[i] = prefix_sum[i-1] + chalk[i]\n remainder = k % prefix_sum[-1]\n \n ...
6
There are `n` students in a class numbered from `0` to `n - 1`. The teacher will give each student a problem starting with the student number `0`, then the student number `1`, and so on until the teacher reaches the student number `n - 1`. After that, the teacher will restart the process, starting with the student numb...
Use two pointers, one pointer for each string. Alternately choose the character from each pointer, and move the pointer upwards.
Python Easy Solution
find-the-student-that-will-replace-the-chalk
0
1
```\ndef chalkReplacer(self, chalk: List[int], k: int) -> int:\n\n\tk %= sum(chalk)\n\n\tfor i in range(len(chalk)):\n\t\tif chalk[i]>k:\n\t\t\treturn i\n\t\tk -= chalk[i]\n```\n
4
There are `n` students in a class numbered from `0` to `n - 1`. The teacher will give each student a problem starting with the student number `0`, then the student number `1`, and so on until the teacher reaches the student number `n - 1`. After that, the teacher will restart the process, starting with the student numb...
Use two pointers, one pointer for each string. Alternately choose the character from each pointer, and move the pointer upwards.
Python | simple O(N)
find-the-student-that-will-replace-the-chalk
0
1
```\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n x = sum(chalk)\n if x<k:\n k = k%x\n if x == k:\n return 0\n i = 0\n n = len(chalk)\n while True:\n if chalk[i]<=k:\n k -= chalk[i]\n ...
4
There are `n` students in a class numbered from `0` to `n - 1`. The teacher will give each student a problem starting with the student number `0`, then the student number `1`, and so on until the teacher reaches the student number `n - 1`. After that, the teacher will restart the process, starting with the student numb...
Use two pointers, one pointer for each string. Alternately choose the character from each pointer, and move the pointer upwards.
[Python3] prefix sums
largest-magic-square
0
1
\n```\nclass Solution:\n def largestMagicSquare(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0]) # dimensions \n rows = [[0]*(n+1) for _ in range(m)] # prefix sum along row\n cols = [[0]*n for _ in range(m+1)] # prefix sum along column\n \n for i in range(m):\n...
7
A `k x k` **magic square** is a `k x k` grid filled with integers such that every row sum, every column sum, and both diagonal sums are **all equal**. The integers in the magic square **do not have to be distinct**. Every `1 x 1` grid is trivially a **magic square**. Given an `m x n` integer `grid`, return _the **size...
If you want to move a ball from box i to box j, you'll need abs(i-j) moves. To move all balls to some box, you can move them one by one. For each box i, iterate on each ball in a box j, and add abs(i-j) to answers[i].
[Python3] prefix sums
largest-magic-square
0
1
\n```\nclass Solution:\n def largestMagicSquare(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0]) # dimensions \n rows = [[0]*(n+1) for _ in range(m)] # prefix sum along row\n cols = [[0]*n for _ in range(m+1)] # prefix sum along column\n \n for i in range(m):\n...
7
There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`. Level **1** of videos are all watched videos by your...
Check all squares in the matrix and find the largest one.
Clean code
largest-magic-square
0
1
The idea is to check all squares.\nSolution is optimized with prefix sums of rows and cols (you can do the same for diagonals, but I was too lazy to do so). The unoptimized part of the code is commented out.\n\n```\nclass Solution:\n def largestMagicSquare(self, grid: List[List[int]]) -> int:\n n, m = len(gri...
0
A `k x k` **magic square** is a `k x k` grid filled with integers such that every row sum, every column sum, and both diagonal sums are **all equal**. The integers in the magic square **do not have to be distinct**. Every `1 x 1` grid is trivially a **magic square**. Given an `m x n` integer `grid`, return _the **size...
If you want to move a ball from box i to box j, you'll need abs(i-j) moves. To move all balls to some box, you can move them one by one. For each box i, iterate on each ball in a box j, and add abs(i-j) to answers[i].
Clean code
largest-magic-square
0
1
The idea is to check all squares.\nSolution is optimized with prefix sums of rows and cols (you can do the same for diagonals, but I was too lazy to do so). The unoptimized part of the code is commented out.\n\n```\nclass Solution:\n def largestMagicSquare(self, grid: List[List[int]]) -> int:\n n, m = len(gri...
0
There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`. Level **1** of videos are all watched videos by your...
Check all squares in the matrix and find the largest one.
Python | Easy to Understand | O(mnmin(m,n)^2)
largest-magic-square
0
1
# Code\n```\nclass Solution:\n def largestMagicSquare(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0]) # dimensions \n rows = [[0]*n for _ in range(m)]\n cols = [[0]*n for _ in range(m)]\n diag = [[0]*n for _ in range(m)]\n anti = [[0]*n for _ in range(m)]\n ...
0
A `k x k` **magic square** is a `k x k` grid filled with integers such that every row sum, every column sum, and both diagonal sums are **all equal**. The integers in the magic square **do not have to be distinct**. Every `1 x 1` grid is trivially a **magic square**. Given an `m x n` integer `grid`, return _the **size...
If you want to move a ball from box i to box j, you'll need abs(i-j) moves. To move all balls to some box, you can move them one by one. For each box i, iterate on each ball in a box j, and add abs(i-j) to answers[i].
Python | Easy to Understand | O(mnmin(m,n)^2)
largest-magic-square
0
1
# Code\n```\nclass Solution:\n def largestMagicSquare(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0]) # dimensions \n rows = [[0]*n for _ in range(m)]\n cols = [[0]*n for _ in range(m)]\n diag = [[0]*n for _ in range(m)]\n anti = [[0]*n for _ in range(m)]\n ...
0
There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`. Level **1** of videos are all watched videos by your...
Check all squares in the matrix and find the largest one.
🐍 DP and Prefix Sum || 97% faster || well-Explained 📌
largest-magic-square
0
1
## IDEA:\nWe simply need prefix sum of all rows and all columns and both the diagonals.\n\nSo of we have that then we can simply for each valid size of square iterate over the matrix\nand check if each row sum , columns sum and both diagonals is same.\n\nIf you want example also then plz tell me.\uD83E\uDD17\n\'\'\'\n\...
5
A `k x k` **magic square** is a `k x k` grid filled with integers such that every row sum, every column sum, and both diagonal sums are **all equal**. The integers in the magic square **do not have to be distinct**. Every `1 x 1` grid is trivially a **magic square**. Given an `m x n` integer `grid`, return _the **size...
If you want to move a ball from box i to box j, you'll need abs(i-j) moves. To move all balls to some box, you can move them one by one. For each box i, iterate on each ball in a box j, and add abs(i-j) to answers[i].
🐍 DP and Prefix Sum || 97% faster || well-Explained 📌
largest-magic-square
0
1
## IDEA:\nWe simply need prefix sum of all rows and all columns and both the diagonals.\n\nSo of we have that then we can simply for each valid size of square iterate over the matrix\nand check if each row sum , columns sum and both diagonals is same.\n\nIf you want example also then plz tell me.\uD83E\uDD17\n\'\'\'\n\...
5
There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`. Level **1** of videos are all watched videos by your...
Check all squares in the matrix and find the largest one.
Python 3 | Very Clean Code, O(min(M, N) ^ 2 * M * N) | Explanation
largest-magic-square
0
1
### Explanation\n- Calculate prefix-sum of row, column, major diagonal, minor diagonal\n- Then, for each edge size, at each valid axis, check if it\'s magic square\n- Time Complexity: `O(min(M, N) ^ 2 * M * N)`, when a `M * N` grid is given. If `M == N`, then `O(M^4)`.\n### Implementation\n```\nclass Solution:\n def...
2
A `k x k` **magic square** is a `k x k` grid filled with integers such that every row sum, every column sum, and both diagonal sums are **all equal**. The integers in the magic square **do not have to be distinct**. Every `1 x 1` grid is trivially a **magic square**. Given an `m x n` integer `grid`, return _the **size...
If you want to move a ball from box i to box j, you'll need abs(i-j) moves. To move all balls to some box, you can move them one by one. For each box i, iterate on each ball in a box j, and add abs(i-j) to answers[i].
Python 3 | Very Clean Code, O(min(M, N) ^ 2 * M * N) | Explanation
largest-magic-square
0
1
### Explanation\n- Calculate prefix-sum of row, column, major diagonal, minor diagonal\n- Then, for each edge size, at each valid axis, check if it\'s magic square\n- Time Complexity: `O(min(M, N) ^ 2 * M * N)`, when a `M * N` grid is given. If `M == N`, then `O(M^4)`.\n### Implementation\n```\nclass Solution:\n def...
2
There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`. Level **1** of videos are all watched videos by your...
Check all squares in the matrix and find the largest one.
[Python3] Prefix Sum - Set - easy understanding
largest-magic-square
0
1
```\ndef largestMagicSquare(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n # 0-index is sum prefix sum of row, 1-index is ps of col, 2-index is ps of top-left to bot-right diagonal, 3-index is ps of bot-left to top-right diagomal\n ps = [[[0, 0, 0, 0] for _ in range(n + 2)]...
2
A `k x k` **magic square** is a `k x k` grid filled with integers such that every row sum, every column sum, and both diagonal sums are **all equal**. The integers in the magic square **do not have to be distinct**. Every `1 x 1` grid is trivially a **magic square**. Given an `m x n` integer `grid`, return _the **size...
If you want to move a ball from box i to box j, you'll need abs(i-j) moves. To move all balls to some box, you can move them one by one. For each box i, iterate on each ball in a box j, and add abs(i-j) to answers[i].
[Python3] Prefix Sum - Set - easy understanding
largest-magic-square
0
1
```\ndef largestMagicSquare(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n # 0-index is sum prefix sum of row, 1-index is ps of col, 2-index is ps of top-left to bot-right diagonal, 3-index is ps of bot-left to top-right diagomal\n ps = [[[0, 0, 0, 0] for _ in range(n + 2)]...
2
There are `n` people, each person has a unique _id_ between `0` and `n-1`. Given the arrays `watchedVideos` and `friends`, where `watchedVideos[i]` and `friends[i]` contain the list of watched videos and the list of friends respectively for the person with `id = i`. Level **1** of videos are all watched videos by your...
Check all squares in the matrix and find the largest one.
O(n): Recursive parsing two expressions + calculate min cost. (30 lines, 90% runtime)
minimum-cost-to-change-the-final-value-of-expression
0
1
# Approach\nParsing the expression right to left.\nEach recursive call with look for:\n- 1 expression (no operation): e1 only\n- 2 expressions (with operation): e2 [op] e1 with \'e2\' being parsed in a recursive call.\n\nand return:\n- val: The evaluation of the expression (0 or 1)\n- cost: The minimum cost to change t...
0
You are given a **valid** boolean expression as a string `expression` consisting of the characters `'1'`,`'0'`,`'&'` (bitwise **AND** operator),`'|'` (bitwise **OR** operator),`'('`, and `')'`. * For example, `"()1|1 "` and `"(1)&() "` are **not valid** while `"1 "`, `"(((1))|(0)) "`, and `"1|(0&(1)) "` are **valid*...
At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal. You should try all scenarios but this will be costy. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence...
Python3: Tree based solution with DP
minimum-cost-to-change-the-final-value-of-expression
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 **valid** boolean expression as a string `expression` consisting of the characters `'1'`,`'0'`,`'&'` (bitwise **AND** operator),`'|'` (bitwise **OR** operator),`'('`, and `')'`. * For example, `"()1|1 "` and `"(1)&() "` are **not valid** while `"1 "`, `"(((1))|(0)) "`, and `"1|(0&(1)) "` are **valid*...
At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal. You should try all scenarios but this will be costy. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence...
Short O(n) DFS in Python with Explanation, Faster than 94%
minimum-cost-to-change-the-final-value-of-expression
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nDivide and conquer can be used to solve this problem. Exploring the number of operations to make the left part to be 0 and 1, and the number of operations to make the right part to be 0 and 1. \n\nTo make the value of an `&` operator either 0 or 1, th...
0
You are given a **valid** boolean expression as a string `expression` consisting of the characters `'1'`,`'0'`,`'&'` (bitwise **AND** operator),`'|'` (bitwise **OR** operator),`'('`, and `')'`. * For example, `"()1|1 "` and `"(1)&() "` are **not valid** while `"1 "`, `"(((1))|(0)) "`, and `"1|(0&(1)) "` are **valid*...
At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal. You should try all scenarios but this will be costy. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence...
Python (Simple DFS)
minimum-cost-to-change-the-final-value-of-expression
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 **valid** boolean expression as a string `expression` consisting of the characters `'1'`,`'0'`,`'&'` (bitwise **AND** operator),`'|'` (bitwise **OR** operator),`'('`, and `')'`. * For example, `"()1|1 "` and `"(1)&() "` are **not valid** while `"1 "`, `"(((1))|(0)) "`, and `"1|(0&(1)) "` are **valid*...
At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal. You should try all scenarios but this will be costy. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence...
[Python3] divide & conquer
minimum-cost-to-change-the-final-value-of-expression
0
1
\n```\nclass Solution:\n def minOperationsToFlip(self, expression: str) -> int:\n loc = {}\n stack = []\n for i in reversed(range(len(expression))):\n if expression[i] == ")": stack.append(i)\n elif expression[i] == "(": loc[stack.pop()] = i \n \n def fn(lo, h...
1
You are given a **valid** boolean expression as a string `expression` consisting of the characters `'1'`,`'0'`,`'&'` (bitwise **AND** operator),`'|'` (bitwise **OR** operator),`'('`, and `')'`. * For example, `"()1|1 "` and `"(1)&() "` are **not valid** while `"1 "`, `"(((1))|(0)) "`, and `"1|(0&(1)) "` are **valid*...
At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal. You should try all scenarios but this will be costy. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence...
Python | dictionary
redistribute-characters-to-make-all-strings-equal
0
1
```\nclass Solution:\n def makeEqual(self, words: List[str]) -> bool:\n map_ = {}\n for word in words:\n for i in word:\n if i not in map_:\n map_[i] = 1\n else:\n map_[i] += 1\n n = len(words)\n for k,v in map...
17
You are given an array of strings `words` (**0-indexed**). In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`. Return `true` _if you can make **every** string in_ `words` _**equal** using **a...
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subse...
PYTHON 3 : | 98.48% | EXPLAINED |TWO EASY SOLUTIONS|
redistribute-characters-to-make-all-strings-equal
0
1
eg --> words = ["abc","aabc","bcc"]\n\n* stp1) join --> "abcaabcbc"\n* stp2) set --> {\'b\', \'a\', \'c\'}\n* stp3) joint.count(\'b\') = 3 , joint.count(\'a\') = 3 , joint.count(\'c\') = 4\n* stp4) as joint.count(\'c\') = 4 therefore it is not multiple of len(words)--->[here 3]\n\tif joint.count(i) % len(words) != 0 ...
21
You are given an array of strings `words` (**0-indexed**). In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`. Return `true` _if you can make **every** string in_ `words` _**equal** using **a...
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subse...
Python solution
redistribute-characters-to-make-all-strings-equal
0
1
```\nclass Solution:\n def makeEqual(self, words: List[str]) -> bool:\n string: str = "".join(words)\n hash_table, _len = {}, len(words)\n\n for letter in string:\n hash_table[letter] = hash_table.get(letter, 0) + 1\n\n for frequency in hash_table.values():\n if freq...
0
You are given an array of strings `words` (**0-indexed**). In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`. Return `true` _if you can make **every** string in_ `words` _**equal** using **a...
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subse...
Python3. 1-liner.
redistribute-characters-to-make-all-strings-equal
0
1
```\nclass Solution:\n def makeEqual(self, words: List[str]) -> bool:\n return True if all(map(lambda x: x[1] % len(words) == 0, Counter(\'\'.join(words)).items())) else False\n```
0
You are given an array of strings `words` (**0-indexed**). In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`. Return `true` _if you can make **every** string in_ `words` _**equal** using **a...
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subse...
Python easy solution
redistribute-characters-to-make-all-strings-equal
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 an array of strings `words` (**0-indexed**). In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`. Return `true` _if you can make **every** string in_ `words` _**equal** using **a...
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subse...
Python: Using Hashmap
redistribute-characters-to-make-all-strings-equal
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 an array of strings `words` (**0-indexed**). In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`. Return `true` _if you can make **every** string in_ `words` _**equal** using **a...
Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subse...
95.96% simplified Python solution
maximum-number-of-removable-characters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n* Figure out a good way to find subsequence given a set of impacted indices\n* Try to expand the set of impacted indices and return max size as answer\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**Subsequence f...
1
You are given two strings `s` and `p` where `p` is a **subsequence** of `s`. You are also given a **distinct 0-indexed** integer array `removable` containing a subset of indices of `s` (`s` is also **0-indexed**). You want to choose an integer `k` (`0 <= k <= removable.length`) such that, after removing `k` characters...
null
🔥[Python 3] BS, beats 100% 🥷🏼
maximum-number-of-removable-characters
0
1
```python3 []\nclass Solution:\n def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:\n l, r = 0, len(removable)\n\n def isEnough(k):\n s_arr = list(s)\n for i in removable[:k]:\n s_arr[i] = \'\'\n return isSubsequence(p, s_arr)\n ...
6
You are given two strings `s` and `p` where `p` is a **subsequence** of `s`. You are also given a **distinct 0-indexed** integer array `removable` containing a subset of indices of `s` (`s` is also **0-indexed**). You want to choose an integer `k` (`0 <= k <= removable.length`) such that, after removing `k` characters...
null
O(nlogn) time | O(k) space | solution explained
maximum-number-of-removable-characters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe range to remove characters is 0 to the size of the removable array. Consider it a sorted array and use binary search to find k (number of removable characters). If we can remove k characters i.e s remains a subsequence of p after remo...
2
You are given two strings `s` and `p` where `p` is a **subsequence** of `s`. You are also given a **distinct 0-indexed** integer array `removable` containing a subset of indices of `s` (`s` is also **0-indexed**). You want to choose an integer `k` (`0 <= k <= removable.length`) such that, after removing `k` characters...
null
[Python3] binary search
maximum-number-of-removable-characters
0
1
\n```\nclass Solution:\n def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:\n mp = {x: i for i, x in enumerate(removable)}\n \n def fn(x):\n """Return True if p is a subseq of s after x removals."""\n k = 0 \n for i, ch in enumerate(s): \n ...
13
You are given two strings `s` and `p` where `p` is a **subsequence** of `s`. You are also given a **distinct 0-indexed** integer array `removable` containing a subset of indices of `s` (`s` is also **0-indexed**). You want to choose an integer `k` (`0 <= k <= removable.length`) such that, after removing `k` characters...
null
[Python3] Binary Search - Easy to understand
maximum-number-of-removable-characters
0
1
```\nclass Solution:\n def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:\n l, r = 0, len(removable)\n while l <= r:\n m = (l + r) >> 1\n d = set(removable[:m])\n i, j = 0, 0\n while i < len(s) and j < len(p):\n if i not in...
7
You are given two strings `s` and `p` where `p` is a **subsequence** of `s`. You are also given a **distinct 0-indexed** integer array `removable` containing a subset of indices of `s` (`s` is also **0-indexed**). You want to choose an integer `k` (`0 <= k <= removable.length`) such that, after removing `k` characters...
null
Python Plain Binary Search
maximum-number-of-removable-characters
0
1
```\nclass Solution:\n def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:\n \n def isSubseq(s,subseq,removed):\n i = 0\n j = 0\n while i<len(s) and j<len(subseq):\n if i in removed or s[i]!= subseq[j]:\n i+=1\n ...
1
You are given two strings `s` and `p` where `p` is a **subsequence** of `s`. You are also given a **distinct 0-indexed** integer array `removable` containing a subset of indices of `s` (`s` is also **0-indexed**). You want to choose an integer `k` (`0 <= k <= removable.length`) such that, after removing `k` characters...
null
Python3 clean Binary Search
maximum-number-of-removable-characters
0
1
\n\n# Code\n```\nclass Solution:\n def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:\n \n \n \n lst=list(s)\n \n def isSubsequence(x,y):\n it=iter(y)\n return all(ch in it for ch in x)\n \n \n def isValid(m):\n...
1
You are given two strings `s` and `p` where `p` is a **subsequence** of `s`. You are also given a **distinct 0-indexed** integer array `removable` containing a subset of indices of `s` (`s` is also **0-indexed**). You want to choose an integer `k` (`0 <= k <= removable.length`) such that, after removing `k` characters...
null
Binary Search
maximum-number-of-removable-characters
0
1
# Code\n```\nclass Solution:\n def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:\n def f(x, s, p):\n # Enter x, and return True if p is still a substring of s of s after the first x subscripts are removed\n s = list(s)\n p = list(p)\n for idx i...
0
You are given two strings `s` and `p` where `p` is a **subsequence** of `s`. You are also given a **distinct 0-indexed** integer array `removable` containing a subset of indices of `s` (`s` is also **0-indexed**). You want to choose an integer `k` (`0 <= k <= removable.length`) such that, after removing `k` characters...
null
Python3 solution
maximum-number-of-removable-characters
0
1
# Code\n```python\nclass Solution:\n def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:\n def isSub(s,p):\n i,j = 0,0\n while i<len(s) and j<len(p):\n if i in removed or s[i]!=p[j]:\n i+=1\n else:\n ...
0
You are given two strings `s` and `p` where `p` is a **subsequence** of `s`. You are also given a **distinct 0-indexed** integer array `removable` containing a subset of indices of `s` (`s` is also **0-indexed**). You want to choose an integer `k` (`0 <= k <= removable.length`) such that, after removing `k` characters...
null
Binary Search For k
maximum-number-of-removable-characters
0
1
# Intuition\nBinary search for k\n# Complexity\n- Time complexity:\n$$O(nlog(n))$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:\n def satisfies(k, sequence):\n iter_s = iter(sequence)\n return a...
0
You are given two strings `s` and `p` where `p` is a **subsequence** of `s`. You are also given a **distinct 0-indexed** integer array `removable` containing a subset of indices of `s` (`s` is also **0-indexed**). You want to choose an integer `k` (`0 <= k <= removable.length`) such that, after removing `k` characters...
null
Python Binary Search
maximum-number-of-removable-characters
0
1
Binary Search k in interval [0, r), where r = len(removable)\nFor each mid, check if removable[:mid+1] could make p a subsequence of s.\nIf True, k could be larger, so we search in the right half; else, search in the left half.\n\n# Complexity\n- Time complexity: O((p+s+r) * logr)\n<!-- Add your time complexity here, e...
0
You are given two strings `s` and `p` where `p` is a **subsequence** of `s`. You are also given a **distinct 0-indexed** integer array `removable` containing a subset of indices of `s` (`s` is also **0-indexed**). You want to choose an integer `k` (`0 <= k <= removable.length`) such that, after removing `k` characters...
null
Python sol with link.
merge-triplets-to-form-target-triplet
0
1
\n# Code\n```\n# https://www.youtube.com/watch?v=kShkQLQZ9K4\nclass Solution:\n def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n res=set()\n for i in range(len(triplets)):\n if triplets[i][0]>target[0] or triplets[i][1]>target[1] or triplets[i][2]>target[2]:\n...
1
A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain. To obtain `target`, you may apply the following opera...
Iterate on each item, and check if each one matches the rule according to the statement.
[Python 3] Greedy + Sort - Simple Solution
merge-triplets-to-form-target-triplet
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...
3
A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain. To obtain `target`, you may apply the following opera...
Iterate on each item, and check if each one matches the rule according to the statement.
Python3 Easy Solution
merge-triplets-to-form-target-triplet
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)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n...
0
A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain. To obtain `target`, you may apply the following opera...
Iterate on each item, and check if each one matches the rule according to the statement.
[Python] One pass O(n) solution with detailed explanation || clear and easy
merge-triplets-to-form-target-triplet
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nFirst, express the question in math terms:\nGiven an array of triplets = (a1, b1, c1), (a2, b2, c2), ... , (an, bn, cn)\nAnd a target = (A, B, C)\nWe need to check if we can find a subset = (ai, bi, ci) i=1->n \nwhere max(ai) = A, max(b...
1
A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain. To obtain `target`, you may apply the following opera...
Iterate on each item, and check if each one matches the rule according to the statement.
Simple Python, Beats 96%
merge-triplets-to-form-target-triplet
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can return true if all the elements of target exist in triplets which do not contain values greater than the other target values.\n\n\n# Code\n```\nclass Solution:\n def mergeTriplets(self, triplets: List[List[int]], target: List[in...
1
A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain. To obtain `target`, you may apply the following opera...
Iterate on each item, and check if each one matches the rule according to the statement.
Simple Python Solution
merge-triplets-to-form-target-triplet
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def mergeTriplets(self, triplets: List[List[int]], t...
1
A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain. To obtain `target`, you may apply the following opera...
Iterate on each item, and check if each one matches the rule according to the statement.
python | implementation O(N)
merge-triplets-to-form-target-triplet
0
1
```\nclass Solution:\n def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n i = 1\n cur = []\n for a,b,c in triplets:\n if a<=target[0] and b<=target[1] and c<= target[2]:\n cur = [a,b,c]\n break\n if not cur:\n ...
4
A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain. To obtain `target`, you may apply the following opera...
Iterate on each item, and check if each one matches the rule according to the statement.
100%! Python Solution 💯
merge-triplets-to-form-target-triplet
0
1
# Intuition\nIf any value of any triplet matches the value in the same position in the target and none of the values of that triplet is greater than the corresponding values of the target then that position can be merged.\n\n# Approach\nGreedy, one-pass\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\n...
0
A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain. To obtain `target`, you may apply the following opera...
Iterate on each item, and check if each one matches the rule according to the statement.
Super Fast Python Solution. Beats 100% of submissions. Easy to understand
merge-triplets-to-form-target-triplet
0
1
# Intuition\nWe can only merge triples by applying a max operation *to every number in each triple*. Therefore, if even a single value is greater than the corresponding target value, we cannot merge that triplet. \n\n# Approach\nIterate through the triplets, apply the (very fast) max operation to all triplets that meet...
0
A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain. To obtain `target`, you may apply the following opera...
Iterate on each item, and check if each one matches the rule according to the statement.
code only
merge-triplets-to-form-target-triplet
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n $$O(n)$$ \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def ...
0
A **triplet** is an array of three integers. You are given a 2D integer array `triplets`, where `triplets[i] = [ai, bi, ci]` describes the `ith` **triplet**. You are also given an integer array `target = [x, y, z]` that describes the **triplet** you want to obtain. To obtain `target`, you may apply the following opera...
Iterate on each item, and check if each one matches the rule according to the statement.
Python: [Intuitive Solution] Simulate rounds using DFS + string map
the-earliest-and-latest-rounds-where-players-compete
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
There is a tournament where `n` players are participating. The players are standing in a single row and are numbered from `1` to `n` based on their **initial** standing position (player `1` is the first player in the row, player `2` is the second player in the row, etc.). The tournament consists of multiple rounds (st...
As the constraints are not large, you can brute force and enumerate all the possibilities.
[Python3] bit-mask dp
the-earliest-and-latest-rounds-where-players-compete
0
1
\n```\nclass Solution:\n def earliestAndLatest(self, n: int, firstPlayer: int, secondPlayer: int) -> List[int]:\n firstPlayer, secondPlayer = firstPlayer-1, secondPlayer-1 # 0-indexed\n \n @cache\n def fn(k, mask): \n """Return earliest and latest rounds."""\n can = ...
8
There is a tournament where `n` players are participating. The players are standing in a single row and are numbered from `1` to `n` based on their **initial** standing position (player `1` is the first player in the row, player `2` is the second player in the row, etc.). The tournament consists of multiple rounds (st...
As the constraints are not large, you can brute force and enumerate all the possibilities.
Python DP Solution | Memoization | Easy to understand
the-earliest-and-latest-rounds-where-players-compete
0
1
\n\n# Code\n```\nclass Solution:\n def earliestAndLatest(self, n: int, firstPlayer: int, secondPlayer: int) -> List[int]:\n @lru_cache(None)\n def dp(left, right, curPlayers, numGamesAlreadyPlayed):\n if left > right: \n dp(right, left, curPlayers, numGamesAlreadyPlayed)\n ...
0
There is a tournament where `n` players are participating. The players are standing in a single row and are numbered from `1` to `n` based on their **initial** standing position (player `1` is the first player in the row, player `2` is the second player in the row, etc.). The tournament consists of multiple rounds (st...
As the constraints are not large, you can brute force and enumerate all the possibilities.
Binary Search Solution with Proper Explanation and Beats 100%
find-a-peak-element-ii
1
1
# Intuition \n<!-- Describe your first thoughts on how to solve this problem. -->\nUse Binary Search\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nReduce 2d array problem to 1d array\n\n# Complexity\n- Time complexity:O(n log(m)), where n rows and m is columns\n<!-- Add your time complexity he...
1
A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom. Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`. Yo...
Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.
Most optimal solution using binary search with explanation
find-a-peak-element-ii
1
1
-->\n\n# Approach\nThe problem is to find a peak element in a 2D grid, which is an element greater than its adjacent neighbors (up, down, left, right). The grid is surrounded by a boundary of -1.\n\nThe provided algorithm uses a binary search approach to find the peak element. It iterates over columns and uses binary s...
6
A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom. Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`. Yo...
Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.
✨✅ (M+N) Solution | Prove me wrong | M+N< MlogN and M+N<NlogM ✅✨
find-a-peak-element-ii
0
1
# Approach\nTraverse Towards the larger element\n\n# Complexity\n- Time complexity:\n O(2*(M+N))=O(M+N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findPeakGrid(self, mat: List...
2
A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom. Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`. Yo...
Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.
Python || 95.26% Faster || O(n log(m)) || Binary Search
find-a-peak-element-ii
0
1
```\nclass Solution:\n def findMax(self, col, matrix, rows):\n maxi = float(\'-inf\')\n rownum = -1\n for i in range(rows):\n if maxi < matrix[i][col]:\n maxi = matrix[i][col]\n rownum = i\n return rownum\n \n def findPeakGrid(self, mat: List...
1
A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom. Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`. Yo...
Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.
Python3 beats 96.22% 🚀🚀 || quibler7
find-a-peak-element-ii
0
1
\n\n# Code\n```\nclass Solution:\n\n def findPeakGrid(self, mat: List[List[int]]) -> List[int]:\n L, H = 0, len(mat) - 1\n #as long as we have at least one row left to consider, continue binary search!\n while L <= H:\n mid = (L + H) // 2\n mid_row = mat[mid]\n #...
2
A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom. Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`. Yo...
Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.
Intuitive (not binary) search
find-a-peak-element-ii
0
1
# Code\n```\nclass Solution:\n def findPeakGrid(self, mat: List[List[int]]) -> List[int]:\n \n # Modify array to look like example test case just for safety\n m = len(mat)\n n = len(mat[0])\n padding = [-1]*(n+2)\n for row in mat:\n row.append(-1)\n row...
2
A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom. Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`. Yo...
Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.
10 lines, beats 100%, O(m + n)
find-a-peak-element-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\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
A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom. Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`. Yo...
Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.
Python 3 | Binary Search | Explanation
find-a-peak-element-ii
0
1
### Explanation\n- Below code is an implementation to `hint` section\n- Start from `mid` column, if a peak is found in this column, return its location\n\t- If peak is on the left, then do a binary search on the left side `columns between [left, mid-1]`\n\t- If peak is on the right, then do a binary search on the right...
22
A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom. Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`. Yo...
Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.
[Python, C++] Brute-force > Optimal | With Explanation
find-a-peak-element-ii
0
1
### Find a Peak Element II\n\nA peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom. You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell.\n\n- Approach\n - Brute-force\n - G...
2
A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom. Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`. Yo...
Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one.
C/C++/Python string ->1 line||0 ms Beats 100%
largest-odd-number-in-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLet $x$ be a natural number expressed in decimal digit representation.\nThen $x$ is odd $\\iff$ its least significant digit is an odd.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nNote `int(\'0\')`=48, it suffic...
9
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** nu...
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and ...
✅☑[C++/Java/Python/JavaScript] || Easy Solution || EXPLAINED🔥
largest-odd-number-in-string
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n1. **Check Last Digit:** Check if the last digit of the input number is odd. If it is, the input number is already the largest odd number. Return the input number in this case.\n1. **Iterative Check**: Starting from the end of the ...
19
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** nu...
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and ...
【Video】Give me 1 minute - How we think about a solution
largest-odd-number-in-string
1
1
# Intuition\nIterate through from the last\n\n---\n\n# Solution Video\n\nhttps://youtu.be/f-hyawcTl8U\n\n\u25A0 Timeline of the video\n\n`0:04` Coding\n`1:18` Time Complexity and Space Complexity\n`1:31` Step by step algorithm with my solution code\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channe...
40
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** nu...
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and ...
✅ One Line Solution
largest-odd-number-in-string
0
1
# Code #1 - The Most Concise\nTime complexity: $$O(n)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def largestOddNumber(self, num: str) -> str:\n return num.rstrip(\'02468\')\n```\n\n# Code #2 - Generator\nTime complexity: $$O(n)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def largestO...
3
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** nu...
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and ...
Finding least significant odd digit
largest-odd-number-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)$$ --...
2
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** nu...
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and ...
Python easy solution with o(n) complexity
largest-odd-number-in-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nchecking the last character\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nif the last character is odd we will return the string itself. if not we will check the second last character and it will go on like tha...
1
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** nu...
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and ...
search from rightmost odd number
largest-odd-number-in-string
1
1
java solution\n```\nclass Solution {\n public String largestOddNumber(String num) {\n for(int i=num.length()-1;i>=0;i--){\n if((num.charAt(i)-\'0\')%2==1){\n return num.substring(0,i+1);\n }\n }\n return "";\n }\n}\n```\n\nc++ solution\n```\nclass Solution...
1
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** nu...
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and ...
🤔 O(n)
largest-odd-number-in-string
0
1
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFind the last index of odd number in the string.\nAny number that ends with odd number is odd number.\n\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add you...
1
You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** nu...
You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and ...
[Python3] math-ish
the-number-of-full-rounds-you-have-played
0
1
\n```\nclass Solution:\n def numberOfRounds(self, startTime: str, finishTime: str) -> int:\n hs, ms = (int(x) for x in startTime.split(":"))\n ts = 60 * hs + ms\n hf, mf = (int(x) for x in finishTime.split(":"))\n tf = 60 * hf + mf\n if 0 <= tf - ts < 15: return 0 # edge case \n ...
20
You are participating in an online chess tournament. There is a chess round that starts every `15` minutes. The first round of the day starts at `00:00`, and after every `15` minutes, a new round starts. * For example, the second round starts at `00:15`, the fourth round starts at `00:45`, and the seventh round star...
First of all, get the distinct characters since we are only interested in those Let's note that there might not be any digits.
easy Python :D
the-number-of-full-rounds-you-have-played
0
1
\n```\nclass Solution:\n def numberOfRounds(self, loginTime: str, logoutTime: str) -> int:\n def time_to_minutes(time_str: str) -> int:\n h, m = map(int, time_str.split(":"))\n return h * 60 + m\n\n login = time_to_minutes(loginTime)\n logout = time_to_minutes(logoutTime)\n...
0
You are participating in an online chess tournament. There is a chess round that starts every `15` minutes. The first round of the day starts at `00:00`, and after every `15` minutes, a new round starts. * For example, the second round starts at `00:15`, the fourth round starts at `00:45`, and the seventh round star...
First of all, get the distinct characters since we are only interested in those Let's note that there might not be any digits.
Python | Mod 15
the-number-of-full-rounds-you-have-played
0
1
\n# Code\n```\nclass Solution:\n def numberOfRounds(self, loginTime: str, logoutTime: str) -> int:\n h, m = loginTime.split(":")\n login = int(h)*60 + int(m)\n h, m = logoutTime.split(":")\n logout = int(h)*60 + int(m)\n res = (logout+(24*60 if logout < login else 0))//15 - (login ...
0
You are participating in an online chess tournament. There is a chess round that starts every `15` minutes. The first round of the day starts at `00:00`, and after every `15` minutes, a new round starts. * For example, the second round starts at `00:15`, the fourth round starts at `00:45`, and the seventh round star...
First of all, get the distinct characters since we are only interested in those Let's note that there might not be any digits.
Python | Bruteforce | Easy Solution
the-number-of-full-rounds-you-have-played
0
1
# Code\n```\nclass Solution:\n def numberOfRounds(self, loginTime: str, logoutTime: str) -> int:\n h, m = loginTime.split(":")\n login = int(h)*60 + int(m)\n h, m = logoutTime.split(":")\n logout = int(h)*60 + int(m)\n if logout < login:\n logout += 60*24\n res = ...
0
You are participating in an online chess tournament. There is a chess round that starts every `15` minutes. The first round of the day starts at `00:00`, and after every `15` minutes, a new round starts. * For example, the second round starts at `00:15`, the fourth round starts at `00:45`, and the seventh round star...
First of all, get the distinct characters since we are only interested in those Let's note that there might not be any digits.
Number of full rounds | Simple Math | O(1)
the-number-of-full-rounds-you-have-played
0
1
# Approach\n1. Convert the time string to minutes\n2. handle logout time for next day\n3. Calculate number of full rounds\n - for login.. Full round starts after next iteration (`ceil`)\n - for logout.. Consider last round only if it\'s full (`floor`)\n4. Handle edge case - If user logs in and out in the same rou...
0
You are participating in an online chess tournament. There is a chess round that starts every `15` minutes. The first round of the day starts at `00:00`, and after every `15` minutes, a new round starts. * For example, the second round starts at `00:15`, the fourth round starts at `00:45`, and the seventh round star...
First of all, get the distinct characters since we are only interested in those Let's note that there might not be any digits.
[Python] straightforward, parse string
the-number-of-full-rounds-you-have-played
0
1
```\nclass Solution:\n def numberOfRounds(self, loginTime: str, logoutTime: str) -> int:\n login = self.to_min(loginTime)\n logout = self.to_min(logoutTime)\n \n if logout < login: # new day after midnight\n logout = logout + 24 * 60\n \n if logout - login < ...
1
You are participating in an online chess tournament. There is a chess round that starts every `15` minutes. The first round of the day starts at `00:00`, and after every `15` minutes, a new round starts. * For example, the second round starts at `00:15`, the fourth round starts at `00:45`, and the seventh round star...
First of all, get the distinct characters since we are only interested in those Let's note that there might not be any digits.
🐍 98% faster || Simple approach || well-explained 📌
count-sub-islands
0
1
## IDEA:\n\uD83D\uDC49 firstly remove all the non-common island\n\uD83D\uDC49 Now count the sub-islands\n\'\'\'\n\n\tclass Solution:\n def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:\n \n m=len(grid1)\n n=len(grid1[0])\n \n def dfs(i,j):\n ...
199
You are given two `m x n` binary matrices `grid1` and `grid2` containing only `0`'s (representing water) and `1`'s (representing land). An **island** is a group of `1`'s connected **4-directionally** (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in `grid2` is considered ...
Using a map, track the expiry times of the tokens. When generating a new token, add it to the map with its expiry time. When renewing a token, check if it's on the map and has not expired yet. If so, update its expiry time. To count unexpired tokens, iterate on the map and check for each token if it's not expired yet.
Fully Efficient Solution in Java 🚀
count-sub-islands
1
1
# Algorithm : \n- Perform DFS on grid2 and store the coordinates of the island.\n- Check if every coordinate stored is \'1\' in grid1.\n- If all the coordinates are 1\'s in grid1 then increment the count.\n- Finally return the count.\n>### *Check the implementation for clear understanding !!*\n---\n# Java Code\n```\ncl...
5
You are given two `m x n` binary matrices `grid1` and `grid2` containing only `0`'s (representing water) and `1`'s (representing land). An **island** is a group of `1`'s connected **4-directionally** (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in `grid2` is considered ...
Using a map, track the expiry times of the tokens. When generating a new token, add it to the map with its expiry time. When renewing a token, check if it's on the map and has not expired yet. If so, update its expiry time. To count unexpired tokens, iterate on the map and check for each token if it's not expired yet.
Easy & Clear Solution Python3 DP
count-sub-islands
0
1
\n\n# Code\n```\nclass Solution:\n def countSubIslands(self, back: List[List[int]], grid: List[List[int]]) -> int:\n m=len(grid)\n n=len(grid[0])\n res=0\n test=True\n def dfs(i,j):\n nonlocal test\n if grid[i][j]==1:\n if back[i][j] != 1:\n ...
6
You are given two `m x n` binary matrices `grid1` and `grid2` containing only `0`'s (representing water) and `1`'s (representing land). An **island** is a group of `1`'s connected **4-directionally** (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in `grid2` is considered ...
Using a map, track the expiry times of the tokens. When generating a new token, add it to the map with its expiry time. When renewing a token, check if it's on the map and has not expired yet. If so, update its expiry time. To count unexpired tokens, iterate on the map and check for each token if it's not expired yet.
python3 solution using bfs beats 99% time 100% space O(M*N),O(M*N)
count-sub-islands
0
1
![sumukha 2023-08-30 at 4.40.11 PM.png](https://assets.leetcode.com/users/images/d7c86a2c-e5e0-4ec5-ab4d-2fe9b6b4c952_1693763034.4553797.png)\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nthe logic here is any island that exists in grid2 being check by `grid2[i][j]` which when 1 enters if co...
3
You are given two `m x n` binary matrices `grid1` and `grid2` containing only `0`'s (representing water) and `1`'s (representing land). An **island** is a group of `1`'s connected **4-directionally** (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in `grid2` is considered ...
Using a map, track the expiry times of the tokens. When generating a new token, add it to the map with its expiry time. When renewing a token, check if it's on the map and has not expired yet. If so, update its expiry time. To count unexpired tokens, iterate on the map and check for each token if it's not expired yet.
Python Elegant & Short | In-place | DFS
count-sub-islands
0
1
\tclass Solution:\n\t\t"""\n\t\tTime: O(n^2)\n\t\tMemory: O(n^2)\n\t\t"""\n\n\t\tLAND = 1\n\t\tWATER = 0\n\n\t\tdef countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:\n\t\t\tm, n = len(grid1), len(grid1[0])\n\n\t\t\tfor i in range(m):\n\t\t\t\tfor j in range(n):\n\t\t\t\t\tif grid2[i][j] ==...
6
You are given two `m x n` binary matrices `grid1` and `grid2` containing only `0`'s (representing water) and `1`'s (representing land). An **island** is a group of `1`'s connected **4-directionally** (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in `grid2` is considered ...
Using a map, track the expiry times of the tokens. When generating a new token, add it to the map with its expiry time. When renewing a token, check if it's on the map and has not expired yet. If so, update its expiry time. To count unexpired tokens, iterate on the map and check for each token if it's not expired yet.
Python 3 || 9 lines, dp , w/explanation || T/M: 100% / 55%
minimum-absolute-difference-queries
0
1
Here\'s how the code works:\n\n- We initialize two empty lists, `ans` and `dp`. `ans` stores the answers for each query, and `dp` is used to keep track of the cumulative count of numbers in the array.\n- The first row of`dp`is initialized as a list of zeros with a length of ``max(nums) + 1``, which ensures that`dp`has ...
3
The **minimum absolute difference** of an array `a` is defined as the **minimum value** of `|a[i] - a[j]|`, where `0 <= i < j < a.length` and `a[i] != a[j]`. If all elements of `a` are the **same**, the minimum absolute difference is `-1`. * For example, the minimum absolute difference of the array `[5,2,3,7,2]` is ...
Find every way to split the array until n groups of 2. Brute force recursion is acceptable. Calculate the gcd of every pair and greedily multiply the largest gcds.
[Python3] binary search
minimum-absolute-difference-queries
0
1
\n```\nclass Solution:\n def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n loc = {}\n for i, x in enumerate(nums): loc.setdefault(x, []).append(i)\n keys = sorted(loc)\n \n ans = []\n for l, r in queries: \n prev, val = 0, inf\n ...
8
The **minimum absolute difference** of an array `a` is defined as the **minimum value** of `|a[i] - a[j]|`, where `0 <= i < j < a.length` and `a[i] != a[j]`. If all elements of `a` are the **same**, the minimum absolute difference is `-1`. * For example, the minimum absolute difference of the array `[5,2,3,7,2]` is ...
Find every way to split the array until n groups of 2. Brute force recursion is acceptable. Calculate the gcd of every pair and greedily multiply the largest gcds.
Python O(100*100*log(N)*Q)
minimum-absolute-difference-queries
0
1
# Code\n```\nclass Solution:\n def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n m = collections.defaultdict(list)\n @functools.lru_cache(maxsize=None)\n def has_number_in_range(num, q):\n A = m[num]\n lo,hi=0,len(A)-1\n while lo<...
0
The **minimum absolute difference** of an array `a` is defined as the **minimum value** of `|a[i] - a[j]|`, where `0 <= i < j < a.length` and `a[i] != a[j]`. If all elements of `a` are the **same**, the minimum absolute difference is `-1`. * For example, the minimum absolute difference of the array `[5,2,3,7,2]` is ...
Find every way to split the array until n groups of 2. Brute force recursion is acceptable. Calculate the gcd of every pair and greedily multiply the largest gcds.
Python solution. Time beats > 90%; space beats 70%.
minimum-absolute-difference-queries
0
1
\n# Approach\nn = len(nums)\nm = len(queries)\nv = number of distinct values (at most 100 in this case)\n\nFor each point i=0,1,2,...,n-1, we store the distinct values v that have occurred in nums[0...i-1] and their counts in distinct_sets[i][v]. For example\n\n1, 1, 2, 3, 3, 4, 2\n\nwill result in\ndistinct_set[0] ={1...
0
The **minimum absolute difference** of an array `a` is defined as the **minimum value** of `|a[i] - a[j]|`, where `0 <= i < j < a.length` and `a[i] != a[j]`. If all elements of `a` are the **same**, the minimum absolute difference is `-1`. * For example, the minimum absolute difference of the array `[5,2,3,7,2]` is ...
Find every way to split the array until n groups of 2. Brute force recursion is acceptable. Calculate the gcd of every pair and greedily multiply the largest gcds.
1909. Remove One Element to Make the Array Strictly Increasing
remove-one-element-to-make-the-array-strictly-increasing
0
1
```\nclass Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n dnums=nums.copy() #make a copy of the original array <nums>\n for i in range(len(nums)-1): #traverse the first pointer <i> in the original array <nums>\n if nums[i]>=nums[i+1]:\n a=nums.pop(i)\n ...
3
Given a **0-indexed** integer array `nums`, return `true` _if it can be made **strictly increasing** after removing **exactly one** element, or_ `false` _otherwise. If the array is already strictly increasing, return_ `true`. The array `nums` is **strictly increasing** if `nums[i - 1] < nums[i]` for each index `(1 <= ...
You can traverse the buildings from the nearest to the ocean to the furthest. Keep with you the maximum to the right while traversing to determine if you can see the ocean or not.
🔥 [Python 3] One pass , beats 80%🥷🏼
remove-one-element-to-make-the-array-strictly-increasing
0
1
Similar to [665. Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array/description/)\n\n```\nclass Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n isRemove = False\n for i in range(1, len(nums)):\n if nums[i] <= nums[i-1]:\n if isRemove: re...
10
Given a **0-indexed** integer array `nums`, return `true` _if it can be made **strictly increasing** after removing **exactly one** element, or_ `false` _otherwise. If the array is already strictly increasing, return_ `true`. The array `nums` is **strictly increasing** if `nums[i - 1] < nums[i]` for each index `(1 <= ...
You can traverse the buildings from the nearest to the ocean to the furthest. Keep with you the maximum to the right while traversing to determine if you can see the ocean or not.
Simple solution in O(n). Beats 99%.
remove-one-element-to-make-the-array-strictly-increasing
0
1
# Approach\nStarting from the second element of the array we check if it is less or equal to the previous one. In this case the array is not strictly increasing and we need to fix it and we have two way to do this:\n - if `nums[i-2] < nums[i] < nums[i-1]` ( e.g 2, 10, 5 (i), 6 ) remove `i-1` (10) fix the situation.\...
6
Given a **0-indexed** integer array `nums`, return `true` _if it can be made **strictly increasing** after removing **exactly one** element, or_ `false` _otherwise. If the array is already strictly increasing, return_ `true`. The array `nums` is **strictly increasing** if `nums[i - 1] < nums[i]` for each index `(1 <= ...
You can traverse the buildings from the nearest to the ocean to the furthest. Keep with you the maximum to the right while traversing to determine if you can see the ocean or not.
Superb Logic With sort with two Approches
remove-one-element-to-make-the-array-strictly-increasing
0
1
```\nclass Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n for i in range(len(nums)):\n temp=nums[:i]+nums[i+1:]\n if temp==sorted(set(temp)):\n return True\n return False\n```\n```\nclass Solution:\n def canBeIncreasing(self, nums: List[int]) -...
5
Given a **0-indexed** integer array `nums`, return `true` _if it can be made **strictly increasing** after removing **exactly one** element, or_ `false` _otherwise. If the array is already strictly increasing, return_ `true`. The array `nums` is **strictly increasing** if `nums[i - 1] < nums[i]` for each index `(1 <= ...
You can traverse the buildings from the nearest to the ocean to the furthest. Keep with you the maximum to the right while traversing to determine if you can see the ocean or not.
[Python3] collect non-conforming indices
remove-one-element-to-make-the-array-strictly-increasing
0
1
\n```\nclass Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n stack = []\n for i in range(1, len(nums)): \n if nums[i-1] >= nums[i]: stack.append(i)\n \n if not stack: return True \n if len(stack) > 1: return False\n i = stack[0]\n ...
18
Given a **0-indexed** integer array `nums`, return `true` _if it can be made **strictly increasing** after removing **exactly one** element, or_ `false` _otherwise. If the array is already strictly increasing, return_ `true`. The array `nums` is **strictly increasing** if `nums[i - 1] < nums[i]` for each index `(1 <= ...
You can traverse the buildings from the nearest to the ocean to the furthest. Keep with you the maximum to the right while traversing to determine if you can see the ocean or not.
[95+%, Python] Extended window
remove-one-element-to-make-the-array-strictly-increasing
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. -->\nIterate over the array until `nums[i-1] < nums[i]` condition is wrong. If the condition is **False**, we extend the window from **2** elements **up to 4** and trying t...
1
Given a **0-indexed** integer array `nums`, return `true` _if it can be made **strictly increasing** after removing **exactly one** element, or_ `false` _otherwise. If the array is already strictly increasing, return_ `true`. The array `nums` is **strictly increasing** if `nums[i - 1] < nums[i]` for each index `(1 <= ...
You can traverse the buildings from the nearest to the ocean to the furthest. Keep with you the maximum to the right while traversing to determine if you can see the ocean or not.
Python easy solution for beginners
remove-one-element-to-make-the-array-strictly-increasing
0
1
```\nclass Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n for i in range(len(nums)):\n temp = nums[:i] + nums[i+1:]\n if sorted(temp) == temp:\n if len(set(temp)) == len(temp):\n return True\n return False
11
Given a **0-indexed** integer array `nums`, return `true` _if it can be made **strictly increasing** after removing **exactly one** element, or_ `false` _otherwise. If the array is already strictly increasing, return_ `true`. The array `nums` is **strictly increasing** if `nums[i - 1] < nums[i]` for each index `(1 <= ...
You can traverse the buildings from the nearest to the ocean to the furthest. Keep with you the maximum to the right while traversing to determine if you can see the ocean or not.
✅ Explained - Simple and Clear Python3 Code✅
remove-all-occurrences-of-a-substring
0
1
# Intuition\nThe problem asks us to repeatedly remove all occurrences of a given substring, \'part\', from a given string, \'s\', until no more occurrences are left. To solve this problem, we can use a simple iterative approach. We keep searching for the leftmost occurrence of \'part\' in \'s\' and remove it until no m...
5
Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed: * Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`. Return `s` _after removing all occurrences of_ `part`. A **substring** is a contiguous seque...
It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones.
Easy solution || beats 100%
remove-all-occurrences-of-a-substring
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 two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed: * Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`. Return `s` _after removing all occurrences of_ `part`. A **substring** is a contiguous seque...
It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones.
Python Beginner, replace() function
remove-all-occurrences-of-a-substring
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)$$ --...
3
Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed: * Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`. Return `s` _after removing all occurrences of_ `part`. A **substring** is a contiguous seque...
It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones.
Python | Easy Solution✅
remove-all-occurrences-of-a-substring
0
1
Solution 1:\n```\ndef removeOccurrences(self, s: str, part: str) -> str:\n while part in s:\n s= s.replace(part,"",1)\n return s\n```\nSolution 2:\n```\ndef removeOccurrences(self, s: str, part: str) -> str:\n while part in s:\n index = s.index(part)\n s = s[:index]...
5
Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed: * Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`. Return `s` _after removing all occurrences of_ `part`. A **substring** is a contiguous seque...
It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones.
Python Solution || 3 lines || 91% beats
remove-all-occurrences-of-a-substring
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)$$ --...
5
Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed: * Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`. Return `s` _after removing all occurrences of_ `part`. A **substring** is a contiguous seque...
It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones.
🔥 DP and DFS | Very Clearly Explained! | O(n) Time
maximum-alternating-subsequence-sum
0
1
***Solution 1: Dynamic Programming***\n\n**Intuition**\nWe can use DP (dynamic programming) to loop through nums and find the biggest alternating subsequence num.\n\n**Algorithm**\nWe first initialize a `n` by `2` matrix where `n = len(nums)`. In a supposed index of `dp[i][j]`, `i` stands for the index of `dp` based on...
9
The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices. * For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`. Given an array `nums`, return _the **maximum alternating sum** of any...
Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can "normalize" goal by offsetting it by the...