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 solution. O(n)
rotating-the-box
0
1
```\nclass Solution:\n def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:\n n = len(box[0])\n ans = [[] for _ in range(n)]\n for row in reversed(box):\n i = 0\n for j, ch in enumerate(row):\n if ch == \'*\':\n for k in range(i...
0
You are given an `m x n` matrix of characters `box` representing a side-view of a box. Each cell of the box is one of the following: * A stone `'#'` * A stationary obstacle `'*'` * Empty `'.'` The box is rotated **90 degrees clockwise**, causing some of the stones to fall due to gravity. Each stone falls down u...
Suppose We can put m boxes on the floor, within all the ways to put the boxes, what’s the maximum number of boxes we can put in? The first box should always start in the corner
Python3 solution
rotating-the-box
0
1
# Intuition\nRotate first, then "apply the gravity". \n\nApplying gravity means starting from the bottom and figuring out how far objects can fall, then making them fall.\n\n# Approach\nFirst, we\'ll rotate the box by copying over the contents to a new box. If the box originally had n rows and m cols, the new box will ...
0
You are given an `m x n` matrix of characters `box` representing a side-view of a box. Each cell of the box is one of the following: * A stone `'#'` * A stationary obstacle `'*'` * Empty `'.'` The box is rotated **90 degrees clockwise**, causing some of the stones to fall due to gravity. Each stone falls down u...
Suppose We can put m boxes on the floor, within all the ways to put the boxes, what’s the maximum number of boxes we can put in? The first box should always start in the corner
Python: Rotate and drop
rotating-the-box
0
1
# Complexity\n- Time complexity:\n$$O(m*n)$$\n\n- Space complexity:\n$$O(m*n)$$\n\n# Code\n```\nclass Solution:\n def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:\n m = len(box)\n n = len(box[0])\n # rotate matrix\n box_r = [[box[r][c] for r in range(m-1,-1,-1)] for c in r...
0
You are given an `m x n` matrix of characters `box` representing a side-view of a box. Each cell of the box is one of the following: * A stone `'#'` * A stationary obstacle `'*'` * Empty `'.'` The box is rotated **90 degrees clockwise**, causing some of the stones to fall due to gravity. Each stone falls down u...
Suppose We can put m boxes on the floor, within all the ways to put the boxes, what’s the maximum number of boxes we can put in? The first box should always start in the corner
[Python3] Readable, Intuitive Solution with Comments || Faster than 84% of Python submissions
rotating-the-box
0
1
```\nclass Solution:\n def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:\n def convert_rows_to_processed_cols(rows):\n def convert_row_to_processed_col(row):\n insert_stone_ptr = len(row) - 1\n i = len(row) - 1\n \n while i ...
0
You are given an `m x n` matrix of characters `box` representing a side-view of a box. Each cell of the box is one of the following: * A stone `'#'` * A stationary obstacle `'*'` * Empty `'.'` The box is rotated **90 degrees clockwise**, causing some of the stones to fall due to gravity. Each stone falls down u...
Suppose We can put m boxes on the floor, within all the ways to put the boxes, what’s the maximum number of boxes we can put in? The first box should always start in the corner
[PYTHON] | ALGORITHM
sum-of-floored-pairs
0
1
\nRuntime: **3561 ms, faster than 73.68%** of Python3 online submissions for Sum of Floored Pairs.\nMemory Usage: **32.6 MB, less than 56.84%** of Python3 online submissions for Sum of Floored Pairs.\n```\n\nclass Solution:\n def sumOfFlooredPairs(self, n: List[int]) -> int:\n f, m, c = Counter(n), max(n), [0...
1
Given an integer array `nums`, return the sum of `floor(nums[i] / nums[j])` for all pairs of indices `0 <= i, j < nums.length` in the array. Since the answer may be too large, return it **modulo** `109 + 7`. The `floor()` function returns the integer part of the division. **Example 1:** **Input:** nums = \[2,5,9\] *...
null
[PYTHON] | ALGORITHM
sum-of-floored-pairs
0
1
\nRuntime: **3561 ms, faster than 73.68%** of Python3 online submissions for Sum of Floored Pairs.\nMemory Usage: **32.6 MB, less than 56.84%** of Python3 online submissions for Sum of Floored Pairs.\n```\n\nclass Solution:\n def sumOfFlooredPairs(self, n: List[int]) -> int:\n f, m, c = Counter(n), max(n), [0...
1
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-index...
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
Python/Python3 solution BruteForce & Optimized solution using Dictionary
sum-of-floored-pairs
0
1
**Brute Foce Solution(Time Limit Exceeded)**\n\nThis solution will work if the length of the elements in the testcase is <50000(5 * 10^4).\nIf it exceeds 50000 it will throw TLE error.\n**Code:**\n```\nclass Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n sumP = 0 #To store the value of Sum...
10
Given an integer array `nums`, return the sum of `floor(nums[i] / nums[j])` for all pairs of indices `0 <= i, j < nums.length` in the array. Since the answer may be too large, return it **modulo** `109 + 7`. The `floor()` function returns the integer part of the division. **Example 1:** **Input:** nums = \[2,5,9\] *...
null
Python/Python3 solution BruteForce & Optimized solution using Dictionary
sum-of-floored-pairs
0
1
**Brute Foce Solution(Time Limit Exceeded)**\n\nThis solution will work if the length of the elements in the testcase is <50000(5 * 10^4).\nIf it exceeds 50000 it will throw TLE error.\n**Code:**\n```\nclass Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n sumP = 0 #To store the value of Sum...
10
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-index...
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
Python most optimized solution
sum-of-floored-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n[[2//2, 2//5, 2//9],\n [5//2, 5//5, 5//9],\n [9//2, 9//5, 9//9]]\n\n let\'s take 9//2 what it represents, it represents that there are total\n of 4 number (2,4,6,8) before 9 that are multiple of 2. so its value \n would be 4. same goes fo...
0
Given an integer array `nums`, return the sum of `floor(nums[i] / nums[j])` for all pairs of indices `0 <= i, j < nums.length` in the array. Since the answer may be too large, return it **modulo** `109 + 7`. The `floor()` function returns the integer part of the division. **Example 1:** **Input:** nums = \[2,5,9\] *...
null
Python most optimized solution
sum-of-floored-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n[[2//2, 2//5, 2//9],\n [5//2, 5//5, 5//9],\n [9//2, 9//5, 9//9]]\n\n let\'s take 9//2 what it represents, it represents that there are total\n of 4 number (2,4,6,8) before 9 that are multiple of 2. so its value \n would be 4. same goes fo...
0
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-index...
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
nlogn solution using maths
sum-of-floored-pairs
0
1
\n\n# Code\n```\nclass Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n n,ans = 2*max(nums) + 11,0\n p,arr = [0 for _ in range(n)],[]\n for i in nums:\n p[i] += 1 \n if p[i] == 1 : arr.append(i)\n arr.sort()\n for i in range(1,n): p[i] += p[i-1] \n for x ...
0
Given an integer array `nums`, return the sum of `floor(nums[i] / nums[j])` for all pairs of indices `0 <= i, j < nums.length` in the array. Since the answer may be too large, return it **modulo** `109 + 7`. The `floor()` function returns the integer part of the division. **Example 1:** **Input:** nums = \[2,5,9\] *...
null
nlogn solution using maths
sum-of-floored-pairs
0
1
\n\n# Code\n```\nclass Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n n,ans = 2*max(nums) + 11,0\n p,arr = [0 for _ in range(n)],[]\n for i in nums:\n p[i] += 1 \n if p[i] == 1 : arr.append(i)\n arr.sort()\n for i in range(1,n): p[i] += p[i-1] \n for x ...
0
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-index...
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
Counting I guesssss
sum-of-floored-pairs
0
1
# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n + max_num * log(max_num))$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(maxnum)$$\n# Code\n```\nclass Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n MOD = 10...
0
Given an integer array `nums`, return the sum of `floor(nums[i] / nums[j])` for all pairs of indices `0 <= i, j < nums.length` in the array. Since the answer may be too large, return it **modulo** `109 + 7`. The `floor()` function returns the integer part of the division. **Example 1:** **Input:** nums = \[2,5,9\] *...
null
Counting I guesssss
sum-of-floored-pairs
0
1
# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n + max_num * log(max_num))$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(maxnum)$$\n# Code\n```\nclass Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n MOD = 10...
0
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-index...
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
Factor Frequency Prefix Sum w/Num Frequency Product | Commented and Explained | O(N) T/S
sum-of-floored-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem description is deceptively simple and at first a brute force even seems a likely and doable option, for which I got 19/51 and then 25/51 with first Time and then Memory limit expired. From this, it becomes more obvious that we...
0
Given an integer array `nums`, return the sum of `floor(nums[i] / nums[j])` for all pairs of indices `0 <= i, j < nums.length` in the array. Since the answer may be too large, return it **modulo** `109 + 7`. The `floor()` function returns the integer part of the division. **Example 1:** **Input:** nums = \[2,5,9\] *...
null
Factor Frequency Prefix Sum w/Num Frequency Product | Commented and Explained | O(N) T/S
sum-of-floored-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem description is deceptively simple and at first a brute force even seems a likely and doable option, for which I got 19/51 and then 25/51 with first Time and then Memory limit expired. From this, it becomes more obvious that we...
0
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-index...
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
Python (Simple Hashmap + Prefix Sum)
sum-of-floored-pairs
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 integer array `nums`, return the sum of `floor(nums[i] / nums[j])` for all pairs of indices `0 <= i, j < nums.length` in the array. Since the answer may be too large, return it **modulo** `109 + 7`. The `floor()` function returns the integer part of the division. **Example 1:** **Input:** nums = \[2,5,9\] *...
null
Python (Simple Hashmap + Prefix Sum)
sum-of-floored-pairs
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
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-index...
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
Python Easy to Understand Solution | Sorting | Binary Search
sum-of-floored-pairs
0
1
\n\n# Code\n```\nclass Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n nums.sort()\n res, mod, cache = 0, 1000000007, {}\n for idx, num in enumerate(nums):\n if num in cache:\n res += cache[num]\n else:\n currentRes, j = 0, i...
0
Given an integer array `nums`, return the sum of `floor(nums[i] / nums[j])` for all pairs of indices `0 <= i, j < nums.length` in the array. Since the answer may be too large, return it **modulo** `109 + 7`. The `floor()` function returns the integer part of the division. **Example 1:** **Input:** nums = \[2,5,9\] *...
null
Python Easy to Understand Solution | Sorting | Binary Search
sum-of-floored-pairs
0
1
\n\n# Code\n```\nclass Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n nums.sort()\n res, mod, cache = 0, 1000000007, {}\n for idx, num in enumerate(nums):\n if num in cache:\n res += cache[num]\n else:\n currentRes, j = 0, i...
0
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-index...
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
Python - 8 lines frequency prefix sum
sum-of-floored-pairs
0
1
```\nclass Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n ans, hi, n, c = 0, max(nums)+1, len(nums), Counter(nums)\n pre = [0] * hi\n for i in range(1, hi):\n pre[i] = pre[i-1] + c[i]\n for num in set(nums):\n for i in range(num, hi, num):\n ...
4
Given an integer array `nums`, return the sum of `floor(nums[i] / nums[j])` for all pairs of indices `0 <= i, j < nums.length` in the array. Since the answer may be too large, return it **modulo** `109 + 7`. The `floor()` function returns the integer part of the division. **Example 1:** **Input:** nums = \[2,5,9\] *...
null
Python - 8 lines frequency prefix sum
sum-of-floored-pairs
0
1
```\nclass Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n ans, hi, n, c = 0, max(nums)+1, len(nums), Counter(nums)\n pre = [0] * hi\n for i in range(1, hi):\n pre[i] = pre[i-1] + c[i]\n for num in set(nums):\n for i in range(num, hi, num):\n ...
4
There is a one-dimensional garden on the x-axis. The garden starts at the point `0` and ends at the point `n`. (i.e The length of the garden is `n`). There are `n + 1` taps located at points `[0, 1, ..., n]` in the garden. Given an integer `n` and an integer array `ranges` of length `n + 1` where `ranges[i]` (0-index...
Find the frequency (number of occurrences) of all elements in the array. For each element, iterate through its multiples and multiply frequencies to find the answer.
Solution with Backtracking in Python3 / TypeScript
sum-of-all-subset-xor-totals
0
1
\n# Intuition\nLet\'s briefly explain what the problem is:\n- there\'s a list of `nums`\n- our goal is to **extract sum** of all **subsets**, that were reduced by **XOR** bit operation between each operands/neighbours.\n\n**Subset** is a part of list, whose indexes could be **shuffled** (**order doesn\'t matter**).\n\n...
1
The **XOR total** of an array is defined as the bitwise `XOR` of **all its elements**, or `0` if the array is **empty**. * For example, the **XOR total** of the array `[2,5,6]` is `2 XOR 5 XOR 6 = 1`. Given an array `nums`, return _the **sum** of all **XOR totals** for every **subset** of_ `nums`. **Note:** Subset...
null
Solution with Backtracking in Python3 / TypeScript
sum-of-all-subset-xor-totals
0
1
\n# Intuition\nLet\'s briefly explain what the problem is:\n- there\'s a list of `nums`\n- our goal is to **extract sum** of all **subsets**, that were reduced by **XOR** bit operation between each operands/neighbours.\n\n**Subset** is a part of list, whose indexes could be **shuffled** (**order doesn\'t matter**).\n\n...
1
You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade node...
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
Python3 || Beats 99.91 % || Bitmask(or)
sum-of-all-subset-xor-totals
0
1
The code calculates the bitwise OR of all numbers in the input list using the bitwise OR operator | and stores it in the variable all_or. It then calculates the total number of possible subsets of nums, which is 2^n where n is the length of the list, using the left bit shift operator << and subtracts 1 from it to get t...
67
The **XOR total** of an array is defined as the bitwise `XOR` of **all its elements**, or `0` if the array is **empty**. * For example, the **XOR total** of the array `[2,5,6]` is `2 XOR 5 XOR 6 = 1`. Given an array `nums`, return _the **sum** of all **XOR totals** for every **subset** of_ `nums`. **Note:** Subset...
null
Python3 || Beats 99.91 % || Bitmask(or)
sum-of-all-subset-xor-totals
0
1
The code calculates the bitwise OR of all numbers in the input list using the bitwise OR operator | and stores it in the variable all_or. It then calculates the total number of possible subsets of nums, which is 2^n where n is the length of the list, using the left bit shift operator << and subtracts 1 from it to get t...
67
You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade node...
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
Python oneliner
sum-of-all-subset-xor-totals
0
1
```py\nclass Solution:\n def subsetXORSum(self, nums: List[int]) -> int:\n \n return sum(reduce(operator.xor, comb) for i in range(1, len(nums)+1) for comb in combinations(nums, i))\n \n```
2
The **XOR total** of an array is defined as the bitwise `XOR` of **all its elements**, or `0` if the array is **empty**. * For example, the **XOR total** of the array `[2,5,6]` is `2 XOR 5 XOR 6 = 1`. Given an array `nums`, return _the **sum** of all **XOR totals** for every **subset** of_ `nums`. **Note:** Subset...
null
Python oneliner
sum-of-all-subset-xor-totals
0
1
```py\nclass Solution:\n def subsetXORSum(self, nums: List[int]) -> int:\n \n return sum(reduce(operator.xor, comb) for i in range(1, len(nums)+1) for comb in combinations(nums, i))\n \n```
2
You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade node...
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
Detailed explanation of the topic
sum-of-all-subset-xor-totals
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code calculates the XOR sum of all possible subsets of the input list nums and returns the result\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Perform bitwise OR operation: ans |= x performs a bitwise OR ...
3
The **XOR total** of an array is defined as the bitwise `XOR` of **all its elements**, or `0` if the array is **empty**. * For example, the **XOR total** of the array `[2,5,6]` is `2 XOR 5 XOR 6 = 1`. Given an array `nums`, return _the **sum** of all **XOR totals** for every **subset** of_ `nums`. **Note:** Subset...
null
Detailed explanation of the topic
sum-of-all-subset-xor-totals
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code calculates the XOR sum of all possible subsets of the input list nums and returns the result\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Perform bitwise OR operation: ans |= x performs a bitwise OR ...
3
You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade node...
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
Best Optimal Solution
sum-of-all-subset-xor-totals
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
The **XOR total** of an array is defined as the bitwise `XOR` of **all its elements**, or `0` if the array is **empty**. * For example, the **XOR total** of the array `[2,5,6]` is `2 XOR 5 XOR 6 = 1`. Given an array `nums`, return _the **sum** of all **XOR totals** for every **subset** of_ `nums`. **Note:** Subset...
null
Best Optimal Solution
sum-of-all-subset-xor-totals
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
You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade node...
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
[Python3] greedy
minimum-number-of-swaps-to-make-the-binary-string-alternating
0
1
\n```\nclass Solution:\n def minSwaps(self, s: str) -> int:\n ones = s.count("1")\n zeros = len(s) - ones \n if abs(ones - zeros) > 1: return -1 # impossible\n \n def fn(x): \n """Return number of swaps if string starts with x."""\n ans = 0 \n for c...
26
Given a binary string `s`, return _the **minimum** number of character swaps to make it **alternating**, or_ `-1` _if it is impossible._ The string is called **alternating** if no two adjacent characters are equal. For example, the strings `"010 "` and `"1010 "` are alternating, while the string `"0100 "` is not. Any...
null
[Python3] greedy
minimum-number-of-swaps-to-make-the-binary-string-alternating
0
1
\n```\nclass Solution:\n def minSwaps(self, s: str) -> int:\n ones = s.count("1")\n zeros = len(s) - ones \n if abs(ones - zeros) > 1: return -1 # impossible\n \n def fn(x): \n """Return number of swaps if string starts with x."""\n ans = 0 \n for c...
26
You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers. * For example, if `nums = [1, 2, 3, 4]`: * `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3...
Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.
Python 3 | Greedy | Explanation
minimum-number-of-swaps-to-make-the-binary-string-alternating
0
1
### Explanation\n- When talking about _**swap**_, it\'s almost always a greedy operation, no easy way around\n- There are only two scenarios, either `010101....` or `101010....`, depends on the length of `s`, you might want to append an extra `0` or `1`\n- Simply count the mismatches and pick the less one, see more exp...
10
Given a binary string `s`, return _the **minimum** number of character swaps to make it **alternating**, or_ `-1` _if it is impossible._ The string is called **alternating** if no two adjacent characters are equal. For example, the strings `"010 "` and `"1010 "` are alternating, while the string `"0100 "` is not. Any...
null
Python 3 | Greedy | Explanation
minimum-number-of-swaps-to-make-the-binary-string-alternating
0
1
### Explanation\n- When talking about _**swap**_, it\'s almost always a greedy operation, no easy way around\n- There are only two scenarios, either `010101....` or `101010....`, depends on the length of `s`, you might want to append an extra `0` or `1`\n- Simply count the mismatches and pick the less one, see more exp...
10
You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers. * For example, if `nums = [1, 2, 3, 4]`: * `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3...
Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.
Python, one and only loop
minimum-number-of-swaps-to-make-the-binary-string-alternating
0
1
\n# Code\n```\nclass Solution:\n def minSwaps(self, s):\n ones_counts = [0, 0] # number of ones in odd indecies and even indecies\n for i in range(len(s)):\n if s[i] == \'1\':\n ones_counts[i%2] += 1\n num_ones = ones_counts[0] + ones_counts[1]\n num_zeros = len(...
1
Given a binary string `s`, return _the **minimum** number of character swaps to make it **alternating**, or_ `-1` _if it is impossible._ The string is called **alternating** if no two adjacent characters are equal. For example, the strings `"010 "` and `"1010 "` are alternating, while the string `"0100 "` is not. Any...
null
Python, one and only loop
minimum-number-of-swaps-to-make-the-binary-string-alternating
0
1
\n# Code\n```\nclass Solution:\n def minSwaps(self, s):\n ones_counts = [0, 0] # number of ones in odd indecies and even indecies\n for i in range(len(s)):\n if s[i] == \'1\':\n ones_counts[i%2] += 1\n num_ones = ones_counts[0] + ones_counts[1]\n num_zeros = len(...
1
You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers. * For example, if `nums = [1, 2, 3, 4]`: * `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3...
Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.
DIFFERENT SOLUTION IN PYTHON
minimum-number-of-swaps-to-make-the-binary-string-alternating
0
1
\n# Code\n```\nclass Solution:\n def minSwaps(self, s: str) -> int:\n if abs((s.count("1")-s.count("0")))>1:\n return -1\n c1=s.count("1")\n c0=s.count("0")\n r=len(s)\n str1=""\n str2=""\n i=0\n while(i<r):\n str1+="1"\n i+=1\n...
0
Given a binary string `s`, return _the **minimum** number of character swaps to make it **alternating**, or_ `-1` _if it is impossible._ The string is called **alternating** if no two adjacent characters are equal. For example, the strings `"010 "` and `"1010 "` are alternating, while the string `"0100 "` is not. Any...
null
DIFFERENT SOLUTION IN PYTHON
minimum-number-of-swaps-to-make-the-binary-string-alternating
0
1
\n# Code\n```\nclass Solution:\n def minSwaps(self, s: str) -> int:\n if abs((s.count("1")-s.count("0")))>1:\n return -1\n c1=s.count("1")\n c0=s.count("0")\n r=len(s)\n str1=""\n str2=""\n i=0\n while(i<r):\n str1+="1"\n i+=1\n...
0
You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers. * For example, if `nums = [1, 2, 3, 4]`: * `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3...
Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.
Python3 Hashmap | Explained
finding-pairs-with-a-certain-sum
0
1
# Intuition\nHashmap.\n\n# Approach\nUse 2 hashmaps to store the frequency of every number from each array.\nWhen adding we just decrease the number of frequency from that second hashmap of the previous number (before adding) and update it with the current value (increasing the freq). We modify the value in the second ...
0
You are given two integer arrays `nums1` and `nums2`. You are tasked to implement a data structure that supports queries of two types: 1. **Add** a positive integer to an element of a given index in the array `nums2`. 2. **Count** the number of pairs `(i, j)` such that `nums1[i] + nums2[j]` equals a given value (`0 ...
Find the minimum spanning tree of the given graph. Root the tree in an arbitrary node and calculate the maximum weight of the edge from each node to the chosen root. To answer a query, find the lca between the two nodes, and find the maximum weight from each of the query nodes to their lca and compare it to the given l...
Python3 Sol using dict.
finding-pairs-with-a-certain-sum
0
1
\n```\nclass FindSumPairs:\n\n def __init__(self, nums1: List[int], nums2: List[int]):\n self.num2=nums2\n self.dict_num1 = collections.Counter(nums1)\n self.dict_num2 = collections.Counter(nums2)\n def add(self, index: int, val: int) -> None:\n old_val = self.num2[index]\n new_...
0
You are given two integer arrays `nums1` and `nums2`. You are tasked to implement a data structure that supports queries of two types: 1. **Add** a positive integer to an element of a given index in the array `nums2`. 2. **Count** the number of pairs `(i, j)` such that `nums1[i] + nums2[j]` equals a given value (`0 ...
Find the minimum spanning tree of the given graph. Root the tree in an arbitrary node and calculate the maximum weight of the edge from each node to the chosen root. To answer a query, find the lca between the two nodes, and find the maximum weight from each of the query nodes to their lca and compare it to the given l...
Python Solution using dictionary
finding-pairs-with-a-certain-sum
0
1
#\n# Code\n```\nclass FindSumPairs:\n\n def __init__(self, nums1: List[int], nums2: List[int]):\n # Keep a copy of nums2 for referencing\n self.num2 = nums2\n\n # Since we only need count of each number occurrences\n # Store nums1 and nums2 as dict counts\n self.dict_num1 = collect...
0
You are given two integer arrays `nums1` and `nums2`. You are tasked to implement a data structure that supports queries of two types: 1. **Add** a positive integer to an element of a given index in the array `nums2`. 2. **Count** the number of pairs `(i, j)` such that `nums1[i] + nums2[j]` equals a given value (`0 ...
Find the minimum spanning tree of the given graph. Root the tree in an arbitrary node and calculate the maximum weight of the edge from each node to the chosen root. To answer a query, find the lca between the two nodes, and find the maximum weight from each of the query nodes to their lca and compare it to the given l...
[Python3] top-down dp
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
0
1
\n```\nclass Solution:\n def rearrangeSticks(self, n: int, k: int) -> int:\n \n @cache \n def fn(n, k): \n """Return number of ways to rearrange n sticks to that k are visible."""\n if n == k: return 1\n if k == 0: return 0\n return ((n-1)*fn(n-1, k) +...
4
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,...
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
[Python3] top-down dp
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
0
1
\n```\nclass Solution:\n def rearrangeSticks(self, n: int, k: int) -> int:\n \n @cache \n def fn(n, k): \n """Return number of ways to rearrange n sticks to that k are visible."""\n if n == k: return 1\n if k == 0: return 0\n return ((n-1)*fn(n-1, k) +...
4
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game. A character is said to be...
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
[Python 3] - Math explanation for deriving top-down DP beats 90%
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
0
1
# Explanation\n\nFirstly, when $n=k$, there is a single way to order the sticks. \n\nNow, notice that the largest stick $$n$$ must be the last visible. \n\n\nThen we ask how many sticks are covered by stick $n$? Since we need at least $k-1$ sticks before $n$ to form the $k-1$ visible sequence, the possible choices are...
0
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,...
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
[Python 3] - Math explanation for deriving top-down DP beats 90%
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
0
1
# Explanation\n\nFirstly, when $n=k$, there is a single way to order the sticks. \n\nNow, notice that the largest stick $$n$$ must be the last visible. \n\n\nThen we ask how many sticks are covered by stick $n$? Since we need at least $k-1$ sticks before $n$ to form the $k-1$ visible sequence, the possible choices are...
0
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game. A character is said to be...
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
Optimized Python O(N*K) Time O(N) Space; Simple Explanation
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
0
1
##### Overview:\n**Paradigm**: Dynamic Programming\n**Input Data Structure(s)**: Integer(s)\n**Auxiliary Data Structure(s)**: Arrays/ArrayLists\n**Core Algorithm(s)**: 2D Bottom-Up Dynamic Programming\n\n\n##### Complexity:\nTime: $$O(N \\times K)$$, to compute `N * K` dp states.\nSpace: $$O(N)$$, to store `2 * N` dp s...
0
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,...
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
Optimized Python O(N*K) Time O(N) Space; Simple Explanation
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
0
1
##### Overview:\n**Paradigm**: Dynamic Programming\n**Input Data Structure(s)**: Integer(s)\n**Auxiliary Data Structure(s)**: Arrays/ArrayLists\n**Core Algorithm(s)**: 2D Bottom-Up Dynamic Programming\n\n\n##### Complexity:\nTime: $$O(N \\times K)$$, to compute `N * K` dp states.\nSpace: $$O(N)$$, to store `2 * N` dp s...
0
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game. A character is said to be...
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
[Python] Place from the back
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
0
1
\n```\nclass Solution:\n def rearrangeSticks(self, n: int, k: int) -> int:\n MOD = 10**9+7\n dp = [[-1 for j in range(k+1)] for i in range(n+1)]\n def dfs(n, k):\n if n==k:\n return 1\n if n==0 or k==0:\n return 0\n if dp[n][k] > -1:...
0
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,...
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
[Python] Place from the back
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
0
1
\n```\nclass Solution:\n def rearrangeSticks(self, n: int, k: int) -> int:\n MOD = 10**9+7\n dp = [[-1 for j in range(k+1)] for i in range(n+1)]\n def dfs(n, k):\n if n==k:\n return 1\n if n==0 or k==0:\n return 0\n if dp[n][k] > -1:...
0
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game. A character is said to be...
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
DP solution with recursion explained
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
0
1
# Intuition\nIt\'s enough to consider two cases of position of 1 in the list. \nThe first one is when 1 takes the first place: then the number f(n,k) (denoting the desired number) when the rray starts with 1 is equal to f(n-1, k-1) as 1 will be visible and among n-1 numbers from 2 to n there should be k-1 visible ones...
0
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,...
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
DP solution with recursion explained
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
0
1
# Intuition\nIt\'s enough to consider two cases of position of 1 in the list. \nThe first one is when 1 takes the first place: then the number f(n,k) (denoting the desired number) when the rray starts with 1 is equal to f(n-1, k-1) as 1 will be visible and among n-1 numbers from 2 to n there should be k-1 visible ones...
0
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game. A character is said to be...
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
Python3 classic DP solution
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
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
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,...
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
Python3 classic DP solution
number-of-ways-to-rearrange-sticks-with-k-sticks-visible
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 playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game. A character is said to be...
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
python3 solution
longer-contiguous-segments-of-ones-than-zeros
0
1
\n```\nclass Solution:\n def checkZeroOnes(self, s: str) -> bool:\n best=collections.defaultdict(int)\n for x,t in groupby(s):\n best[x]=max(best[x],len(list(t)))\n \n return best["1"]>best["0"] \n```
1
Given a binary string `s`, return `true` _if the **longest** contiguous segment of_ `1`'_s is **strictly longer** than the **longest** contiguous segment of_ `0`'_s in_ `s`, or return `false` _otherwise_. * For example, in `s = "110100010 "` the longest continuous segment of `1`s has length `2`, and the longest cont...
null
✅ 96% || Python3 || 🚀Slicing || ⭐️ Thoroughly Explanation ⭐️
longer-contiguous-segments-of-ones-than-zeros
0
1
# Intuition\n![Screenshot from 2023-11-11 12-11-12.png](https://assets.leetcode.com/users/images/3d22e768-d4f3-44a1-b56f-d0dc37315154_1699686691.2478716.png)\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- Tim...
1
Given a binary string `s`, return `true` _if the **longest** contiguous segment of_ `1`'_s is **strictly longer** than the **longest** contiguous segment of_ `0`'_s in_ `s`, or return `false` _otherwise_. * For example, in `s = "110100010 "` the longest continuous segment of `1`s has length `2`, and the longest cont...
null
Python3 | Time: O(n) | Space: O(1) | Beats 100% solutions in time
longer-contiguous-segments-of-ones-than-zeros
0
1
```\nclass Solution:\n def checkZeroOnes(self, s: str) -> bool:\n best_one, best_zero, current_one, current_zero = 0, 0, 0, 0\n \n for i in s:\n if i == "1":\n current_zero = 0\n current_one += 1\n else:\n current_zero += 1\n ...
61
Given a binary string `s`, return `true` _if the **longest** contiguous segment of_ `1`'_s is **strictly longer** than the **longest** contiguous segment of_ `0`'_s in_ `s`, or return `false` _otherwise_. * For example, in `s = "110100010 "` the longest continuous segment of `1`s has length `2`, and the longest cont...
null
Python | Easy Solution✅
longer-contiguous-segments-of-ones-than-zeros
0
1
```\ndef checkZeroOnes(self, s: str) -> bool:\n one_list = s.split("0")\n zero_list = s.split("1")\n \n one_max = max(one_list, key=len)\n zero_max = max(zero_list, key=len)\n \n if len(one_max) > len(zero_max):\n return True\n else:\n return...
12
Given a binary string `s`, return `true` _if the **longest** contiguous segment of_ `1`'_s is **strictly longer** than the **longest** contiguous segment of_ `0`'_s in_ `s`, or return `false` _otherwise_. * For example, in `s = "110100010 "` the longest continuous segment of `1`s has length `2`, and the longest cont...
null
Python oneliner
longer-contiguous-segments-of-ones-than-zeros
0
1
```\nclass Solution:\n def checkZeroOnes(self, s: str) -> bool:\n return len(max(s.split(\'0\'),key=len)) > len(max(s.split(\'1\'),key=len))\n```
3
Given a binary string `s`, return `true` _if the **longest** contiguous segment of_ `1`'_s is **strictly longer** than the **longest** contiguous segment of_ `0`'_s in_ `s`, or return `false` _otherwise_. * For example, in `s = "110100010 "` the longest continuous segment of `1`s has length `2`, and the longest cont...
null
Python beginner friendly solution using split()
longer-contiguous-segments-of-ones-than-zeros
0
1
```\nclass Solution:\n def checkZeroOnes(self, s: str) -> bool:\n one_seg = sorted(s.split("0"), key=len)\n zero_seg = sorted(s.split("1"), key=len)\n return len(one_seg[-1]) > len(zero_seg[-1])
2
Given a binary string `s`, return `true` _if the **longest** contiguous segment of_ `1`'_s is **strictly longer** than the **longest** contiguous segment of_ `0`'_s in_ `s`, or return `false` _otherwise_. * For example, in `s = "110100010 "` the longest continuous segment of `1`s has length `2`, and the longest cont...
null
Python ✅😎✅ || Faster than 99.27% || Memory beats 97.32%
longer-contiguous-segments-of-ones-than-zeros
0
1
# Code\n```\nclass Solution:\n def checkZeroOnes(self, s: str) -> bool:\n zero, one = \'\', \'\'\n mZ, mO = 0, 0\n last = str(int(not int(s[-1])))\n\n for c in s + last:\n if c == \'1\':\n mZ = max(len(zero), mZ)\n zero = \'\'\n one ...
2
Given a binary string `s`, return `true` _if the **longest** contiguous segment of_ `1`'_s is **strictly longer** than the **longest** contiguous segment of_ `0`'_s in_ `s`, or return `false` _otherwise_. * For example, in `s = "110100010 "` the longest continuous segment of `1`s has length `2`, and the longest cont...
null
Easy solution in Python using Regular Expressions
longer-contiguous-segments-of-ones-than-zeros
0
1
```\nfrom re import findall\nclass Solution(object):\n def checkZeroOnes(self, s):\n """\n :type s: str\n :rtype: bool\n """\n o = 0\n z = 0\n try:\n o = len(max(findall("11*",s)))\n z = len(max(findall("00*",s)))\n except:\n No...
3
Given a binary string `s`, return `true` _if the **longest** contiguous segment of_ `1`'_s is **strictly longer** than the **longest** contiguous segment of_ `0`'_s in_ `s`, or return `false` _otherwise_. * For example, in `s = "110100010 "` the longest continuous segment of `1`s has length `2`, and the longest cont...
null
Python || Easy to understand||Beginner solution
longer-contiguous-segments-of-ones-than-zeros
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 binary string `s`, return `true` _if the **longest** contiguous segment of_ `1`'_s is **strictly longer** than the **longest** contiguous segment of_ `0`'_s in_ `s`, or return `false` _otherwise_. * For example, in `s = "110100010 "` the longest continuous segment of `1`s has length `2`, and the longest cont...
null
Longer Contiguous Segments of Ones than Zeros
longer-contiguous-segments-of-ones-than-zeros
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 binary string `s`, return `true` _if the **longest** contiguous segment of_ `1`'_s is **strictly longer** than the **longest** contiguous segment of_ `0`'_s in_ `s`, or return `false` _otherwise_. * For example, in `s = "110100010 "` the longest continuous segment of `1`s has length `2`, and the longest cont...
null
C++/Python Koko-like solutions with small searching region
minimum-speed-to-arrive-on-time
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLike solving the binary search problem\n[875. Koko Eating Bananas\n](https://leetcode.com/problems/koko-eating-bananas/solutions/3685871/w-explanation-easy-binary-search-c-solution/)\n# Approach\n<!-- Describe your approach to solving the...
7
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. E...
null
C++/Python Koko-like solutions with small searching region
minimum-speed-to-arrive-on-time
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLike solving the binary search problem\n[875. Koko Eating Bananas\n](https://leetcode.com/problems/koko-eating-bananas/solutions/3685871/w-explanation-easy-binary-search-c-solution/)\n# Approach\n<!-- Describe your approach to solving the...
7
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you s...
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
Python3 👍||⚡99/99 faster beats, 11 lines🔥|| clean solution ||
minimum-speed-to-arrive-on-time
0
1
![image.png](https://assets.leetcode.com/users/images/b88e2aad-dabb-4eac-afd0-759a7cc70942_1690342594.5715153.png)\n\n\n# Complexity\n- Time complexity: O(m*log(n))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n...
4
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. E...
null
Python3 👍||⚡99/99 faster beats, 11 lines🔥|| clean solution ||
minimum-speed-to-arrive-on-time
0
1
![image.png](https://assets.leetcode.com/users/images/b88e2aad-dabb-4eac-afd0-759a7cc70942_1690342594.5715153.png)\n\n\n# Complexity\n- Time complexity: O(m*log(n))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n...
4
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you s...
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
🚂 [VIDEO] Beats 95% 🚀 All Aboard the Coding Express: Finding the Minimum Speed with Binary Search
minimum-speed-to-arrive-on-time
1
1
# Intuition\nUpon reading this problem, it quickly becomes clear that there\'s a time constraint on the total journey to the office. This hints towards optimizing the speed of travel. Since we need to find the minimum speed, it seems like a good fit for a binary search algorithm, where we iteratively refine our search ...
3
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. E...
null
🚂 [VIDEO] Beats 95% 🚀 All Aboard the Coding Express: Finding the Minimum Speed with Binary Search
minimum-speed-to-arrive-on-time
1
1
# Intuition\nUpon reading this problem, it quickly becomes clear that there\'s a time constraint on the total journey to the office. This hints towards optimizing the speed of travel. Since we need to find the minimum speed, it seems like a good fit for a binary search algorithm, where we iteratively refine our search ...
3
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you s...
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
Easy intuitive two function solution. Beats 90%
minimum-speed-to-arrive-on-time
0
1
# Intuition\nThis problem seemed very clearly to be a two pointer / binary search problem. We need to find the lowest value which satisfy certain constraints.\n# Approach\nIntially was to check if it is possible to arrive on time.\nIf there are more trains than hours+1, it is impossible to arrive on time. \n# Complexit...
2
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. E...
null
Easy intuitive two function solution. Beats 90%
minimum-speed-to-arrive-on-time
0
1
# Intuition\nThis problem seemed very clearly to be a two pointer / binary search problem. We need to find the lowest value which satisfy certain constraints.\n# Approach\nIntially was to check if it is possible to arrive on time.\nIf there are more trains than hours+1, it is impossible to arrive on time. \n# Complexit...
2
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you s...
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
99% Faster Python Solution | Clean code
minimum-speed-to-arrive-on-time
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is quite a classic problem at least on leetcode. We do binary search on the possible solutions in this case is the speed. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe problem has no solutions if the leng...
2
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. E...
null
99% Faster Python Solution | Clean code
minimum-speed-to-arrive-on-time
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is quite a classic problem at least on leetcode. We do binary search on the possible solutions in this case is the speed. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe problem has no solutions if the leng...
2
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you s...
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
Beats 96.92% in time 🔥🔥🔥
minimum-speed-to-arrive-on-time
0
1
\n# Code\n```\nimport math\n\nclass Solution:\n def minSpeedOnTime(self, dist: List[int], hour: float) -> int:\n len_path = len(dist)\n max_dist = max(dist)\n # Paths that will have to the next full hour takes 1 hour each\n if len_path - 1 >= hour:\n return -1\n # If # o...
1
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. E...
null
Beats 96.92% in time 🔥🔥🔥
minimum-speed-to-arrive-on-time
0
1
\n# Code\n```\nimport math\n\nclass Solution:\n def minSpeedOnTime(self, dist: List[int], hour: float) -> int:\n len_path = len(dist)\n max_dist = max(dist)\n # Paths that will have to the next full hour takes 1 hour each\n if len_path - 1 >= hour:\n return -1\n # If # o...
1
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you s...
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
Python short and clean. BinarySearch. Functional programming.
minimum-speed-to-arrive-on-time
0
1
# Complexity\n- Time complexity: $$O(n \\cdot log(k))$$\n\n- Space complexity: $$O(1)$$\n\nwhere,\n`n is length of dist array`,\n`k is maximum speed possible, i.e 1e7`\n\n# Code\n```python\nclass Solution:\n def minSpeedOnTime(self, dist: list[int], hour: float) -> int:\n n = len(dist)\n if hour <= n -...
1
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. E...
null
Python short and clean. BinarySearch. Functional programming.
minimum-speed-to-arrive-on-time
0
1
# Complexity\n- Time complexity: $$O(n \\cdot log(k))$$\n\n- Space complexity: $$O(1)$$\n\nwhere,\n`n is length of dist array`,\n`k is maximum speed possible, i.e 1e7`\n\n# Code\n```python\nclass Solution:\n def minSpeedOnTime(self, dist: list[int], hour: float) -> int:\n n = len(dist)\n if hour <= n -...
1
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you s...
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
Binary search in C++/python beats 100% using tighter limits
minimum-speed-to-arrive-on-time
0
1
# Intuition\nThe approach I used is a simple binary search, as everybody did. But to get a slight performance improvement, I calculate boundaries for the speed instead of using hard-coded 1 to `1e7` boundary.\n\nWe are given a sequence of distances `dist` denoted as $a_n$, and maximum time `hour` denoted as $c$.\nThen ...
1
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. E...
null
Binary search in C++/python beats 100% using tighter limits
minimum-speed-to-arrive-on-time
0
1
# Intuition\nThe approach I used is a simple binary search, as everybody did. But to get a slight performance improvement, I calculate boundaries for the speed instead of using hard-coded 1 to `1e7` boundary.\n\nWe are given a sequence of distances `dist` denoted as $a_n$, and maximum time `hour` denoted as $c$.\nThen ...
1
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you s...
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
Binary_search.py
minimum-speed-to-arrive-on-time
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
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. E...
null
Binary_search.py
minimum-speed-to-arrive-on-time
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you s...
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
Python 3 | Binary Search | Runtime beats 89%
minimum-speed-to-arrive-on-time
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAccording to the task\'s description:\n- Speed ranges between $$1$$ and $$10^7$$ km/h.\n- We don\'t need to wait additional time after the last train.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse binary sear...
1
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. E...
null
Python 3 | Binary Search | Runtime beats 89%
minimum-speed-to-arrive-on-time
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAccording to the task\'s description:\n- Speed ranges between $$1$$ and $$10^7$$ km/h.\n- We don\'t need to wait additional time after the last train.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse binary sear...
1
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you s...
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
[Simple & Elegant] [O(n) time] [O(maxJump) space] Linear scan using sliding window
jump-game-vii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor computing if any index i is reachable from index 0 or not, we only need the reachability information of indices in the range (i-maxJump, i-1). This is because if index i is reachable and has a path from index 0, then it has to have a ...
3
You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions are fulfilled: * `i + minJump <= j <= min(i + maxJump, s.length - 1)`, and * `s[j]...
Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest
python | 100% faster, 5 methods with explanations
jump-game-vii
0
1
Before I get into the specifics of each method there are 3 cases I checked which make solving the puzzle easier. First, if the target itself can\'t be landed on then there can\'t be a solution. Second, if minJump and maxJump are the same, then there\'s only 1 possible path through the string, does it work? And finally,...
18
You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions are fulfilled: * `i + minJump <= j <= min(i + maxJump, s.length - 1)`, and * `s[j]...
Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest
Clean, Fast Python3 | 2 Pointer | O(n) Time & Space
jump-game-vii
0
1
Please upvote if it helps!\n```\nclass Solution:\n def canReach(self, s: str, minJump: int, maxJump: int) -> bool:\n if s[-1] == \'1\':\n return False\n n, end = len(s), minJump\n reach = [True] + [False] * (n - 1)\n for i in range(n):\n if reach[i]:\n ...
5
You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions are fulfilled: * `i + minJump <= j <= min(i + maxJump, s.length - 1)`, and * `s[j]...
Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest
Top-Down and Bottom-Up
stone-game-viii
0
1
Regardless of how the game was played till now, ending a move with stone `i` will add sum of all `[0.. i]` stones to your score. So, we first compute a prefix sum to get scores in O(1); in other words, `st[i]` will be a sum of all stones `[0..i]`.\n\nThe first player can take all stones and call it a day if all values ...
55
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of...
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a ...
python3 O(n) dynamic programming + prefixsum
stone-game-viii
0
1
Notes:\n\n1. Don\'t use memoization. N limit 10e5 implies an O(n) algorithm, and max of suffix psum[i-1] - dp[i] can actually be stored rather than calculated for every new index.\n2. the max so far should be updated only for indices greater than 1, as we are not allowed to remove only 1 stone at a time.\n\n\n# Code\n`...
0
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of...
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a ...
Simple Python solution
stone-game-viii
0
1
# Intuition\n\nYou can reformulate the game as follows. Alice and Bob are subsequently choose an index $1<i_1<i_2\\dots<i_n=\\text{len(stones)}$ and they receive the sum\n$$\n s_{i_k} = \\sum_{0\\leq j < i_k} \\text{stones}_j\n$$\nThe game ends when there is no more possible selection ($i_n=\\text{len}(stones)$).\n\...
0
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of...
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a ...
removal game modification ez to read and grasp btches
stone-game-viii
0
1
\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def stoneGameVIII(self, st: List[int]) -> int:\n pref=[st[0]]\n for i in st[1:]:\n pref.append(pref[-1]+i)\n n=len(st)\n print(pref)\n dp=[-1]*n\n def rec(l):\n i...
0
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of...
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a ...
Python (Simple DP)
stone-game-viii
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
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of...
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a ...
6 lines python - O(n) time and O(1) space, fater than 99%
stone-game-viii
0
1
```\nclass Solution:\n def stoneGameVIII(self, stones: List[int]) -> int: \n s = sum(stones) \n dp = s\n for i in range(len(stones)-2, 0, -1):\n s -= stones[i+1]\n dp = max(dp, s - dp) \n return dp\n```
2
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of...
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a ...
Python3 Bottom Up O(N) Solution | Very Short
stone-game-viii
0
1
The concept\n* Collect a ```prefix sum``` of the stone values to refer to later at constant time\n* Generate ```dp``` array with the total sum of stone values (aka, score if all the stones are picked)\n* Iterate backwards on the ```dp``` array keeping track of the biggest result seen so far\n* For ```current result```,...
1
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of...
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a ...
Python || Easy || Beats 80 % || Hashmap
substrings-of-size-three-with-distinct-characters
0
1
# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def countGoodSubstrings(self, s: str) -> int:\n\n l = 0\n r = 2\n count=0\n\n while(r<len(s)):\n new = {}\n for i in range(l,r+1):\n new[s[i]] =...
1
A string is **good** if there are no repeated characters. Given a string `s`​​​​​, return _the number of **good substrings** of length **three** in_ `s`​​​​​​. Note that if there are multiple occurrences of the same substring, every occurrence should be counted. A **substring** is a contiguous sequence of characters...
Set each water cell to be 0. The height of each cell is limited by its closest water cell. Perform a multi-source BFS with all the water cells as sources.
Python || Easy || Beats 80 % || Hashmap
substrings-of-size-three-with-distinct-characters
0
1
# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def countGoodSubstrings(self, s: str) -> int:\n\n l = 0\n r = 2\n count=0\n\n while(r<len(s)):\n new = {}\n for i in range(l,r+1):\n new[s[i]] =...
1
You are given a binary string `binary`. A **subsequence** of `binary` is considered **good** if it is **not empty** and has **no leading zeros** (with the exception of `"0 "`). Find the number of **unique good subsequences** of `binary`. * For example, if `binary = "001 "`, then all the **good** subsequences are `[...
Try using a set to find out the number of distinct characters in a substring.
Optimal sliding window O(N)
substrings-of-size-three-with-distinct-characters
0
1
# Code\n```\nclass Solution:\n def countGoodSubstrings(self, s: str) -> int:\n if len(s) < 3:\n return 0\n a = s[0]\n b = s[1]\n c = s[2]\n count = int(a != b and b !=c and c != a)\n\n for i in range(3, len(s)):\n a = b\n b = c\n c...
2
A string is **good** if there are no repeated characters. Given a string `s`​​​​​, return _the number of **good substrings** of length **three** in_ `s`​​​​​​. Note that if there are multiple occurrences of the same substring, every occurrence should be counted. A **substring** is a contiguous sequence of characters...
Set each water cell to be 0. The height of each cell is limited by its closest water cell. Perform a multi-source BFS with all the water cells as sources.
Optimal sliding window O(N)
substrings-of-size-three-with-distinct-characters
0
1
# Code\n```\nclass Solution:\n def countGoodSubstrings(self, s: str) -> int:\n if len(s) < 3:\n return 0\n a = s[0]\n b = s[1]\n c = s[2]\n count = int(a != b and b !=c and c != a)\n\n for i in range(3, len(s)):\n a = b\n b = c\n c...
2
You are given a binary string `binary`. A **subsequence** of `binary` is considered **good** if it is **not empty** and has **no leading zeros** (with the exception of `"0 "`). Find the number of **unique good subsequences** of `binary`. * For example, if `binary = "001 "`, then all the **good** subsequences are `[...
Try using a set to find out the number of distinct characters in a substring.
Unpredicted Logic Python
substrings-of-size-three-with-distinct-characters
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
A string is **good** if there are no repeated characters. Given a string `s`​​​​​, return _the number of **good substrings** of length **three** in_ `s`​​​​​​. Note that if there are multiple occurrences of the same substring, every occurrence should be counted. A **substring** is a contiguous sequence of characters...
Set each water cell to be 0. The height of each cell is limited by its closest water cell. Perform a multi-source BFS with all the water cells as sources.