title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
Python3 Beats 94%
most-visited-sector-in-a-circular-track
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 `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rounds[i - 1]` and ends at sector `rounds[i]`. For example, round 1 starts at ...
Imagine that startTime[i] and endTime[i] form an interval (i.e. [startTime[i], endTime[i]]). The answer is how many times the queryTime laid in those mentioned intervals.
C++/Java Frequency Count O(n+m) vs Python sort 1 line||3ms Beats 100%
maximum-number-of-coins-you-can-get
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse frequency count instead of sorting.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSince you can decide each turn for which triple are choosen.\nLet Bob pick the min n/3 piles. Alice & you choose the max 2n/3 pi...
11
There are `3n` piles of coins of varying size, you and your friends will take piles of coins as follows: * In each step, you will choose **any** `3` piles of coins (not necessarily consecutive). * Of your choice, Alice will pick the pile with the maximum number of coins. * You will pick the next pile with the ma...
Store each word and their relative position. Then, sort them by length of words in case of tie by their original order.
😎🚀 Beats 98% | Detailed Explaination 🔥🦅 | C++ | JAVA | PYTHON | JS
maximum-number-of-coins-you-can-get
1
1
# Intuition\nUPVOTE IF YOU FOUND THIS HELPFUL !!!\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. SORT THE PILES VECTOR IN DECREASING ORDER.\n2. WE CAN TAKE ANY THREE NO.S SO HERE WE TAKE TWO LARGE NUMBERS FOR ALICE AND YOU, AND 1 SMALL NUMBER FOR BOB WHICH IS FROM ENDPOINT OF PIL...
3
There are `3n` piles of coins of varying size, you and your friends will take piles of coins as follows: * In each step, you will choose **any** `3` piles of coins (not necessarily consecutive). * Of your choice, Alice will pick the pile with the maximum number of coins. * You will pick the next pile with the ma...
Store each word and their relative position. Then, sort them by length of words in case of tie by their original order.
【Video】Give me 4 minutes - How we think about a solution
maximum-number-of-coins-you-can-get
1
1
# Intuition\nSort input array.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/HPzfCHfWPlY\n\n\u25A0 Timeline\u3000of the video\n`0:04` Two key points to solve this question\n`1:46` Demonstrate how it works\n`3:17` Coding\n`4:14` Time Complexity and Space Complexity\n`4:33` Summary of the algorithm with my solution code...
42
There are `3n` piles of coins of varying size, you and your friends will take piles of coins as follows: * In each step, you will choose **any** `3` piles of coins (not necessarily consecutive). * Of your choice, Alice will pick the pile with the maximum number of coins. * You will pick the next pile with the ma...
Store each word and their relative position. Then, sort them by length of words in case of tie by their original order.
Simple Python implementation
maximum-number-of-coins-you-can-get
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to get the sum of coins that we can pick\nFor each Iteration, we get 1 min pile and 2 max piles to maximize the coins that we pick. \n\n# Approach\n1. Sort the piles array\n2. Create a subarray of all the coins that we can pick\n3...
3
There are `3n` piles of coins of varying size, you and your friends will take piles of coins as follows: * In each step, you will choose **any** `3` piles of coins (not necessarily consecutive). * Of your choice, Alice will pick the pile with the maximum number of coins. * You will pick the next pile with the ma...
Store each word and their relative position. Then, sort them by length of words in case of tie by their original order.
python3 Solution
maximum-number-of-coins-you-can-get
0
1
\n```\nclass Solution:\n def maxCoins(self, piles: List[int]) -> int:\n piles.sort()\n q=collections.deque(piles)\n ans=0\n while len(q)>0:\n q.popleft()\n q.pop()\n ans+=q[-1]\n q.pop()\n return ans \n```
3
There are `3n` piles of coins of varying size, you and your friends will take piles of coins as follows: * In each step, you will choose **any** `3` piles of coins (not necessarily consecutive). * Of your choice, Alice will pick the pile with the maximum number of coins. * You will pick the next pile with the ma...
Store each word and their relative position. Then, sort them by length of words in case of tie by their original order.
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥
maximum-number-of-coins-you-can-get
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Greedy Simulation with Deque)***\n1. Sort the `piles` in ascending order as we want to optimize the number of coins we can get.\n1. Utilize a deque (double-ended queue) for efficient removal of the maximum and ...
2
There are `3n` piles of coins of varying size, you and your friends will take piles of coins as follows: * In each step, you will choose **any** `3` piles of coins (not necessarily consecutive). * Of your choice, Alice will pick the pile with the maximum number of coins. * You will pick the next pile with the ma...
Store each word and their relative position. Then, sort them by length of words in case of tie by their original order.
Linear Solution in Python3, using counting sort
maximum-number-of-coins-you-can-get
0
1
# Approach\nThe optimal for *us* could be the sum of **the second most coins of each run**, thus using greedy.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(m)$$, where $$m$$ is `max(piles)`\n\n# Code\n```\nclass Solution:\n def maxCoins(self, piles: List[int]) -> int:\n cnt = [0] ...
2
There are `3n` piles of coins of varying size, you and your friends will take piles of coins as follows: * In each step, you will choose **any** `3` piles of coins (not necessarily consecutive). * Of your choice, Alice will pick the pile with the maximum number of coins. * You will pick the next pile with the ma...
Store each word and their relative position. Then, sort them by length of words in case of tie by their original order.
Simple python solution
maximum-number-of-coins-you-can-get
0
1
# Code\n```\nclass Solution:\n def maxCoins(self, piles: List[int]) -> int:\n sum=0\n piles.sort()\n for i in range(len(piles)//3):\n sum+=piles[-i*2-2]\n return sum\n```
2
There are `3n` piles of coins of varying size, you and your friends will take piles of coins as follows: * In each step, you will choose **any** `3` piles of coins (not necessarily consecutive). * Of your choice, Alice will pick the pile with the maximum number of coins. * You will pick the next pile with the ma...
Store each word and their relative position. Then, sort them by length of words in case of tie by their original order.
Easy Code to Understand
maximum-number-of-coins-you-can-get
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTo maximize the sum of the trio of numbers - the greatest, second greatest, and smallest, we need to sort the piles. Assume Alice takes the greatest number, you take the second greatest, and Bob is left with the smallest.\n\...
16
There are `3n` piles of coins of varying size, you and your friends will take piles of coins as follows: * In each step, you will choose **any** `3` piles of coins (not necessarily consecutive). * Of your choice, Alice will pick the pile with the maximum number of coins. * You will pick the next pile with the ma...
Store each word and their relative position. Then, sort them by length of words in case of tie by their original order.
Clean and beginner-friendly 6 line greedy solution
maximum-number-of-coins-you-can-get
0
1
# Intuition\nNotice that Bob would only take the smallest amount of coins.\nSo after sorting, the first n piles of coins would be taken by Bob.\nWe can then simplify the problem, as the other piles of coins are only shared between Amy and us.\nSince Amy always gets the most coins, we could only get the second-largest p...
1
There are `3n` piles of coins of varying size, you and your friends will take piles of coins as follows: * In each step, you will choose **any** `3` piles of coins (not necessarily consecutive). * Of your choice, Alice will pick the pile with the maximum number of coins. * You will pick the next pile with the ma...
Store each word and their relative position. Then, sort them by length of words in case of tie by their original order.
🤦‍♂️Shortest Code simple approach... check it...🤦‍♂️...
maximum-number-of-coins-you-can-get
1
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 are `3n` piles of coins of varying size, you and your friends will take piles of coins as follows: * In each step, you will choose **any** `3` piles of coins (not necessarily consecutive). * Of your choice, Alice will pick the pile with the maximum number of coins. * You will pick the next pile with the ma...
Store each word and their relative position. Then, sort them by length of words in case of tie by their original order.
faster than 99% of python solutions||sorting||greedy||array||
maximum-number-of-coins-you-can-get
0
1
**Problem:**\n\nYou are playing a game with your friends Alice and Bob. There are 3n piles of coins of varying size. In each step of the game, you will choose any 3 piles of coins. Alice will then pick the pile with the maximum number of coins, you will pick the next pile with the maximum number of coins, and Bob will ...
1
There are `3n` piles of coins of varying size, you and your friends will take piles of coins as follows: * In each step, you will choose **any** `3` piles of coins (not necessarily consecutive). * Of your choice, Alice will pick the pile with the maximum number of coins. * You will pick the next pile with the ma...
Store each word and their relative position. Then, sort them by length of words in case of tie by their original order.
Ranges Accounting
find-latest-group-of-size-m
0
1
# Approach\nFirst of all we make the task opposite - we assume having string of ones and go through ```arr``` from back to begin.\nWe have ```ranges```, firstly consisted of one range [1, n], representing ranges of ones. \nThen step by step we put zeros in our string which split ranges of ones into slaller ranges. Afte...
1
Given an array `arr` that represents a permutation of numbers from `1` to `n`. You have a binary string of size `n` that initially has all its bits set to zero. At each step `i` (assuming both the binary string and `arr` are 1-indexed) from `1` to `n`, the bit at position `arr[i]` is set to `1`. You are also given an...
Use hashing to convert company names in numbers and then for each list check if this is a subset of any other list. In order to check if a list is a subset of another list, use two pointers technique to get a linear solution for this task. The total complexity will be O(n^2 * m) where n is the number of lists and m is ...
Ranges Accounting
find-latest-group-of-size-m
0
1
# Approach\nFirst of all we make the task opposite - we assume having string of ones and go through ```arr``` from back to begin.\nWe have ```ranges```, firstly consisted of one range [1, n], representing ranges of ones. \nThen step by step we put zeros in our string which split ranges of ones into slaller ranges. Afte...
1
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`. Return _the number of **consistent** strings in the array_ `words`. **Example 1:** **Input:** allowed = "ab ", words = \[...
Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map.
Union Find || Python
find-latest-group-of-size-m
0
1
```\nclass Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n n = len(arr)\n parent = {index:index for index in range(1, n+ 1)}\n explored,size = [0]*(n + 1), [0]*(n+1)\n ans, self.cnt = -1, 0\n def find(x):\n if x == parent[x]:return x\n p...
0
Given an array `arr` that represents a permutation of numbers from `1` to `n`. You have a binary string of size `n` that initially has all its bits set to zero. At each step `i` (assuming both the binary string and `arr` are 1-indexed) from `1` to `n`, the bit at position `arr[i]` is set to `1`. You are also given an...
Use hashing to convert company names in numbers and then for each list check if this is a subset of any other list. In order to check if a list is a subset of another list, use two pointers technique to get a linear solution for this task. The total complexity will be O(n^2 * m) where n is the number of lists and m is ...
Union Find || Python
find-latest-group-of-size-m
0
1
```\nclass Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n n = len(arr)\n parent = {index:index for index in range(1, n+ 1)}\n explored,size = [0]*(n + 1), [0]*(n+1)\n ans, self.cnt = -1, 0\n def find(x):\n if x == parent[x]:return x\n p...
0
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`. Return _the number of **consistent** strings in the array_ `words`. **Example 1:** **Input:** allowed = "ab ", words = \[...
Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map.
Python, no fancy techniques, simply dictionary.
find-latest-group-of-size-m
0
1
# Code\n```\nclass Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n\n # Let\'s put all the seen intervals into a dict. \n # We put both ways of an interval into the dict so we can\n # find the intervals from both end in O(1) time. \n # We keep track of how many inter...
0
Given an array `arr` that represents a permutation of numbers from `1` to `n`. You have a binary string of size `n` that initially has all its bits set to zero. At each step `i` (assuming both the binary string and `arr` are 1-indexed) from `1` to `n`, the bit at position `arr[i]` is set to `1`. You are also given an...
Use hashing to convert company names in numbers and then for each list check if this is a subset of any other list. In order to check if a list is a subset of another list, use two pointers technique to get a linear solution for this task. The total complexity will be O(n^2 * m) where n is the number of lists and m is ...
Python, no fancy techniques, simply dictionary.
find-latest-group-of-size-m
0
1
# Code\n```\nclass Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n\n # Let\'s put all the seen intervals into a dict. \n # We put both ways of an interval into the dict so we can\n # find the intervals from both end in O(1) time. \n # We keep track of how many inter...
0
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`. Return _the number of **consistent** strings in the array_ `words`. **Example 1:** **Input:** allowed = "ab ", words = \[...
Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map.
Python Recursion
find-latest-group-of-size-m
0
1
In this approach algorithm starts from the end - binary string is full of ones. Iterating over list from the last index sets bit to 0 and divide binary string into two parts. Alghorithm checks length of these parts and if they are m length return current step. In the other case continues recurrence call.\n\n\n# Code\n\...
0
Given an array `arr` that represents a permutation of numbers from `1` to `n`. You have a binary string of size `n` that initially has all its bits set to zero. At each step `i` (assuming both the binary string and `arr` are 1-indexed) from `1` to `n`, the bit at position `arr[i]` is set to `1`. You are also given an...
Use hashing to convert company names in numbers and then for each list check if this is a subset of any other list. In order to check if a list is a subset of another list, use two pointers technique to get a linear solution for this task. The total complexity will be O(n^2 * m) where n is the number of lists and m is ...
Python Recursion
find-latest-group-of-size-m
0
1
In this approach algorithm starts from the end - binary string is full of ones. Iterating over list from the last index sets bit to 0 and divide binary string into two parts. Alghorithm checks length of these parts and if they are m length return current step. In the other case continues recurrence call.\n\n\n# Code\n\...
0
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`. Return _the number of **consistent** strings in the array_ `words`. **Example 1:** **Input:** allowed = "ab ", words = \[...
Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map.
Python Greedy Solution
find-latest-group-of-size-m
0
1
```\nclass Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n cur = [0] * len(arr)\n right = [-1] * len(arr)\n left = [-1] * len(arr)\n groups = [0] * len(arr)\n res = -1\n\n for i in range(len(arr)):\n cur[arr[i]-1] = 1\n \n ...
0
Given an array `arr` that represents a permutation of numbers from `1` to `n`. You have a binary string of size `n` that initially has all its bits set to zero. At each step `i` (assuming both the binary string and `arr` are 1-indexed) from `1` to `n`, the bit at position `arr[i]` is set to `1`. You are also given an...
Use hashing to convert company names in numbers and then for each list check if this is a subset of any other list. In order to check if a list is a subset of another list, use two pointers technique to get a linear solution for this task. The total complexity will be O(n^2 * m) where n is the number of lists and m is ...
Python Greedy Solution
find-latest-group-of-size-m
0
1
```\nclass Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n cur = [0] * len(arr)\n right = [-1] * len(arr)\n left = [-1] * len(arr)\n groups = [0] * len(arr)\n res = -1\n\n for i in range(len(arr)):\n cur[arr[i]-1] = 1\n \n ...
0
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`. Return _the number of **consistent** strings in the array_ `words`. **Example 1:** **Input:** allowed = "ab ", words = \[...
Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map.
Python3 DP solution.
find-latest-group-of-size-m
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe idea is to keep track of the positions of the 1s in the array and the length of the consecutive 1s to the left and right of them. If the length of left or right is equal to m, we have found the latest step. \n# Approach\n<!-- Describe...
1
Given an array `arr` that represents a permutation of numbers from `1` to `n`. You have a binary string of size `n` that initially has all its bits set to zero. At each step `i` (assuming both the binary string and `arr` are 1-indexed) from `1` to `n`, the bit at position `arr[i]` is set to `1`. You are also given an...
Use hashing to convert company names in numbers and then for each list check if this is a subset of any other list. In order to check if a list is a subset of another list, use two pointers technique to get a linear solution for this task. The total complexity will be O(n^2 * m) where n is the number of lists and m is ...
Python3 DP solution.
find-latest-group-of-size-m
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe idea is to keep track of the positions of the 1s in the array and the length of the consecutive 1s to the left and right of them. If the length of left or right is equal to m, we have found the latest step. \n# Approach\n<!-- Describe...
1
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`. Return _the number of **consistent** strings in the array_ `words`. **Example 1:** **Input:** allowed = "ab ", words = \[...
Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map.
✅ || tried my best to explain O(n) solution || python ||
find-latest-group-of-size-m
0
1
```\nclass Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n \n \n if m == len(arr): # if the length of group we want is equal to length of arr than in the end eventually we are getting the group of length == m and latest step will be the last step\n \n ...
4
Given an array `arr` that represents a permutation of numbers from `1` to `n`. You have a binary string of size `n` that initially has all its bits set to zero. At each step `i` (assuming both the binary string and `arr` are 1-indexed) from `1` to `n`, the bit at position `arr[i]` is set to `1`. You are also given an...
Use hashing to convert company names in numbers and then for each list check if this is a subset of any other list. In order to check if a list is a subset of another list, use two pointers technique to get a linear solution for this task. The total complexity will be O(n^2 * m) where n is the number of lists and m is ...
✅ || tried my best to explain O(n) solution || python ||
find-latest-group-of-size-m
0
1
```\nclass Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n \n \n if m == len(arr): # if the length of group we want is equal to length of arr than in the end eventually we are getting the group of length == m and latest step will be the last step\n \n ...
4
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`. Return _the number of **consistent** strings in the array_ `words`. **Example 1:** **Input:** allowed = "ab ", words = \[...
Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map.
[Python / Golang] Simple DP Solution with a Trick for Python
stone-game-v
0
1
**Idea**\nThe idea is straight forward. we just try out all the possibilities to find the answer. Naive brute force solution will lead to O(n!) complexity, so we need to store the interim results to improve the complexity to O(n^3).\n\n**A trick for slower languages**\nSince I got TLE for the O(n^3) solution in Python....
13
There are several stones **arranged in a row**, and each stone has an associated value which is an integer given in the array `stoneValue`. In each round of the game, Alice divides the row into **two non-empty rows** (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the value...
If there is an optimal solution, you can always move the circle so that two points lie on the boundary of the circle. When the radius is fixed, you can find either 0 or 1 or 2 circles that pass two given points at the same time. Loop for each pair of points and find the center of the circle, after that count the number...
[Python / Golang] Simple DP Solution with a Trick for Python
stone-game-v
0
1
**Idea**\nThe idea is straight forward. we just try out all the possibilities to find the answer. Naive brute force solution will lead to O(n!) complexity, so we need to store the interim results to improve the complexity to O(n^3).\n\n**A trick for slower languages**\nSince I got TLE for the O(n^3) solution in Python....
13
You are given an integer array `nums` sorted in **non-decreasing** order. Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]` _and all the other elements in the array._ In other words, `result[i...
We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming.
Python O(n^2) optimized solution. O(n^3) cannot pass.
stone-game-v
0
1
Python is slow sometimes!\n\nTraditional DP: \n```\nfor i in (0, length): \n\tfor j in (0, length): \n\t\tfor k in (i, j): \n\t\t\tdp[i][j] = dp[i][k] + s[i][k]] or dp[k+1][j] + s[k+1][j]\n```\n\nThe hardest thing for us to optimize the O(n^3) is finding a way to reduce the innest loop for k in (i, j), but it\'s not so...
6
There are several stones **arranged in a row**, and each stone has an associated value which is an integer given in the array `stoneValue`. In each round of the game, Alice divides the row into **two non-empty rows** (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the value...
If there is an optimal solution, you can always move the circle so that two points lie on the boundary of the circle. When the radius is fixed, you can find either 0 or 1 or 2 circles that pass two given points at the same time. Loop for each pair of points and find the center of the circle, after that count the number...
Python O(n^2) optimized solution. O(n^3) cannot pass.
stone-game-v
0
1
Python is slow sometimes!\n\nTraditional DP: \n```\nfor i in (0, length): \n\tfor j in (0, length): \n\t\tfor k in (i, j): \n\t\t\tdp[i][j] = dp[i][k] + s[i][k]] or dp[k+1][j] + s[k+1][j]\n```\n\nThe hardest thing for us to optimize the O(n^3) is finding a way to reduce the innest loop for k in (i, j), but it\'s not so...
6
You are given an integer array `nums` sorted in **non-decreasing** order. Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]` _and all the other elements in the array._ In other words, `result[i...
We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming.
Python3 Iterative Solution
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
```python\ndef containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n\ti = 0\n\twhile i <= len(arr)-1:\n\t\tp = arr[i:i+m]\n\t\tif p * k == arr[i:i+m*k]:\n\t\t\treturn True\n\n\t\ti += 1\n\n\treturn False\n```\n\ntrungnguyen276\'s solution (optimized)\n\n```python\ndef containsPattern(self, arr: List[int], m:...
56
Given an array of positive integers `arr`, find a pattern of length `m` that is repeated `k` or more times. A **pattern** is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times **consecutively** without overlapping. A pattern is defined by its length and the number of rep...
First extract the words of the sentence. Check for each word if searchWord occurs at index 0, if so return the index of this word (1-indexed) If searchWord doesn't exist as a prefix of any word return the default value (-1).
Python3 Iterative Solution
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
```python\ndef containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n\ti = 0\n\twhile i <= len(arr)-1:\n\t\tp = arr[i:i+m]\n\t\tif p * k == arr[i:i+m*k]:\n\t\t\treturn True\n\n\t\ti += 1\n\n\treturn False\n```\n\ntrungnguyen276\'s solution (optimized)\n\n```python\ndef containsPattern(self, arr: List[int], m:...
56
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** n...
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
[Python3] O(n) time O(m) space (With explanation)
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
**Just as the hint mentioned, a few key points:**\n1) The pattern must appear consecutively.\n2) No need to loop till the end\n\n**Code:**\n```\nclass Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n n = len(arr)\n max_start_point = n - m * k\n\t\t# If there is an answer...
5
Given an array of positive integers `arr`, find a pattern of length `m` that is repeated `k` or more times. A **pattern** is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times **consecutively** without overlapping. A pattern is defined by its length and the number of rep...
First extract the words of the sentence. Check for each word if searchWord occurs at index 0, if so return the index of this word (1-indexed) If searchWord doesn't exist as a prefix of any word return the default value (-1).
[Python3] O(n) time O(m) space (With explanation)
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
**Just as the hint mentioned, a few key points:**\n1) The pattern must appear consecutively.\n2) No need to loop till the end\n\n**Code:**\n```\nclass Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n n = len(arr)\n max_start_point = n - m * k\n\t\t# If there is an answer...
5
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** n...
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
[Python3] Sliding Window | Iterative
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
Check for each subarray of size m if it consecutively exists and the frequency matches to k\n\n```\ndef containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n n = len(arr)\n for i in range(n-m+1):\n j = i + m\n pat = arr[i: j]\n # freq = 0\n start = 0\...
5
Given an array of positive integers `arr`, find a pattern of length `m` that is repeated `k` or more times. A **pattern** is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times **consecutively** without overlapping. A pattern is defined by its length and the number of rep...
First extract the words of the sentence. Check for each word if searchWord occurs at index 0, if so return the index of this word (1-indexed) If searchWord doesn't exist as a prefix of any word return the default value (-1).
[Python3] Sliding Window | Iterative
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
Check for each subarray of size m if it consecutively exists and the frequency matches to k\n\n```\ndef containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n n = len(arr)\n for i in range(n-m+1):\n j = i + m\n pat = arr[i: j]\n # freq = 0\n start = 0\...
5
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** n...
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
Beats 97.14% of users with Python3
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
# Code\n```\nclass Solution:\n def containsPattern(self, arr: List[int], m: int, k: int, start: int = 0) -> bool:\n # bruteforce solution\n # 34ms\n # Beats 93.65% of users with Python3\n prev, temp = None, []\n for i in range(start, len(arr), m):\n val = arr[i:i+m]\n ...
0
Given an array of positive integers `arr`, find a pattern of length `m` that is repeated `k` or more times. A **pattern** is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times **consecutively** without overlapping. A pattern is defined by its length and the number of rep...
First extract the words of the sentence. Check for each word if searchWord occurs at index 0, if so return the index of this word (1-indexed) If searchWord doesn't exist as a prefix of any word return the default value (-1).
Beats 97.14% of users with Python3
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
# Code\n```\nclass Solution:\n def containsPattern(self, arr: List[int], m: int, k: int, start: int = 0) -> bool:\n # bruteforce solution\n # 34ms\n # Beats 93.65% of users with Python3\n prev, temp = None, []\n for i in range(start, len(arr), m):\n val = arr[i:i+m]\n ...
0
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** n...
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
HashMap solution
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe keep track of the last previous index the pattern was found, see if it is consecutive with the previous index , add one or set it as latest in different cases. We also keep track of the maximum values obtained by each pattern consecuti...
0
Given an array of positive integers `arr`, find a pattern of length `m` that is repeated `k` or more times. A **pattern** is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times **consecutively** without overlapping. A pattern is defined by its length and the number of rep...
First extract the words of the sentence. Check for each word if searchWord occurs at index 0, if so return the index of this word (1-indexed) If searchWord doesn't exist as a prefix of any word return the default value (-1).
HashMap solution
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe keep track of the last previous index the pattern was found, see if it is consecutive with the previous index , add one or set it as latest in different cases. We also keep track of the maximum values obtained by each pattern consecuti...
0
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** n...
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
Python one-line solution beats 65%
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCompare all sublists of length m multiplied by number of occurrences k and see if the concatenated sublist exists in the array\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space ...
0
Given an array of positive integers `arr`, find a pattern of length `m` that is repeated `k` or more times. A **pattern** is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times **consecutively** without overlapping. A pattern is defined by its length and the number of rep...
First extract the words of the sentence. Check for each word if searchWord occurs at index 0, if so return the index of this word (1-indexed) If searchWord doesn't exist as a prefix of any word return the default value (-1).
Python one-line solution beats 65%
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCompare all sublists of length m multiplied by number of occurrences k and see if the concatenated sublist exists in the array\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space ...
0
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** n...
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
Easy to understand Python3 solution
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an array of positive integers `arr`, find a pattern of length `m` that is repeated `k` or more times. A **pattern** is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times **consecutively** without overlapping. A pattern is defined by its length and the number of rep...
First extract the words of the sentence. Check for each word if searchWord occurs at index 0, if so return the index of this word (1-indexed) If searchWord doesn't exist as a prefix of any word return the default value (-1).
Easy to understand Python3 solution
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** n...
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
easy python3 solution
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
\n# Complexity\n- Time complexity:\n- O(N*M^2)\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 containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n n=len(arr)\n ...
0
Given an array of positive integers `arr`, find a pattern of length `m` that is repeated `k` or more times. A **pattern** is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times **consecutively** without overlapping. A pattern is defined by its length and the number of rep...
First extract the words of the sentence. Check for each word if searchWord occurs at index 0, if so return the index of this word (1-indexed) If searchWord doesn't exist as a prefix of any word return the default value (-1).
easy python3 solution
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
\n# Complexity\n- Time complexity:\n- O(N*M^2)\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 containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n n=len(arr)\n ...
0
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** n...
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
Solution by Python
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an array of positive integers `arr`, find a pattern of length `m` that is repeated `k` or more times. A **pattern** is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times **consecutively** without overlapping. A pattern is defined by its length and the number of rep...
First extract the words of the sentence. Check for each word if searchWord occurs at index 0, if so return the index of this word (1-indexed) If searchWord doesn't exist as a prefix of any word return the default value (-1).
Solution by Python
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** n...
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
easy solution
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an array of positive integers `arr`, find a pattern of length `m` that is repeated `k` or more times. A **pattern** is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times **consecutively** without overlapping. A pattern is defined by its length and the number of rep...
First extract the words of the sentence. Check for each word if searchWord occurs at index 0, if so return the index of this word (1-indexed) If searchWord doesn't exist as a prefix of any word return the default value (-1).
easy solution
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** n...
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
Straightforward Python Solution
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
\n\n# Code\n```\nclass Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n i = 0\n while i < len(arr)-1:\n p = arr[i:i+m]\n if p*k == arr[i:i+m*k]:\n return True\n i += 1\n return False\n```
0
Given an array of positive integers `arr`, find a pattern of length `m` that is repeated `k` or more times. A **pattern** is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times **consecutively** without overlapping. A pattern is defined by its length and the number of rep...
First extract the words of the sentence. Check for each word if searchWord occurs at index 0, if so return the index of this word (1-indexed) If searchWord doesn't exist as a prefix of any word return the default value (-1).
Straightforward Python Solution
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
\n\n# Code\n```\nclass Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n i = 0\n while i < len(arr)-1:\n p = arr[i:i+m]\n if p*k == arr[i:i+m*k]:\n return True\n i += 1\n return False\n```
0
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** n...
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
Python easy solution via classic for loop
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code iterates through the given array arr and checks for patterns of length m that are repeated k or more times consecutively. It compares each element at index i with the element at index i + m to identify patterns.\n\n# Approach\n<!...
0
Given an array of positive integers `arr`, find a pattern of length `m` that is repeated `k` or more times. A **pattern** is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times **consecutively** without overlapping. A pattern is defined by its length and the number of rep...
First extract the words of the sentence. Check for each word if searchWord occurs at index 0, if so return the index of this word (1-indexed) If searchWord doesn't exist as a prefix of any word return the default value (-1).
Python easy solution via classic for loop
detect-pattern-of-length-m-repeated-k-or-more-times
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code iterates through the given array arr and checks for patterns of length m that are repeated k or more times consecutively. It compares each element at index i with the element at index i + m to identify patterns.\n\n# Approach\n<!...
0
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** n...
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
[Python3/Go/Java] Dynamic Programming O(N) time O(1) space
maximum-length-of-subarray-with-positive-product
0
1
### Explanation\n"pos[i]", "neg[i]" represent longest consecutive numbers ending with nums[i] forming a positive/negative product.\n\n#### Complexity\n`time`: O(N)\n`space`: O(N)\n\n#### Python3:\n\n```python\ndef getMaxLen(self, nums: List[int]) -> int:\n\tn = len(nums)\n\tpos, neg = [0] * n, [0] * n\n\tif nums[0] > 0...
142
Given an array of integers `nums`, find the maximum length of a subarray where the product of all its elements is positive. A subarray of an array is a consecutive sequence of zero or more values taken out of that array. Return _the maximum length of a subarray with positive product_. **Example 1:** **Input:** nums...
Keep a window of size k and maintain the number of vowels in it. Keep moving the window and update the number of vowels while moving. Answer is max number of vowels of any window.
[Python3/Go/Java] Dynamic Programming O(N) time O(1) space
maximum-length-of-subarray-with-positive-product
0
1
### Explanation\n"pos[i]", "neg[i]" represent longest consecutive numbers ending with nums[i] forming a positive/negative product.\n\n#### Complexity\n`time`: O(N)\n`space`: O(N)\n\n#### Python3:\n\n```python\ndef getMaxLen(self, nums: List[int]) -> int:\n\tn = len(nums)\n\tpos, neg = [0] * n, [0] * n\n\tif nums[0] > 0...
142
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, they can **remove** either the leftmost stone or the rightmost stone from the row and receive points equal to the **sum** of the remaining stones' values in the row. The winner is the ...
Split the whole array into subarrays by zeroes since a subarray with positive product cannot contain any zero. If the subarray has even number of negative numbers, the whole subarray has positive product. Otherwise, we have two choices, either - remove the prefix till the first negative element in this subarray, or rem...
[Python3] 7-line O(N) time & O(1) space
maximum-length-of-subarray-with-positive-product
0
1
Define two counters `pos` and `neg` as the length of positive and negative products ending at current element. \n\n```\nclass Solution:\n def getMaxLen(self, nums: List[int]) -> int:\n ans = pos = neg = 0\n for x in nums: \n if x > 0: pos, neg = 1 + pos, 1 + neg if neg else 0\n el...
68
Given an array of integers `nums`, find the maximum length of a subarray where the product of all its elements is positive. A subarray of an array is a consecutive sequence of zero or more values taken out of that array. Return _the maximum length of a subarray with positive product_. **Example 1:** **Input:** nums...
Keep a window of size k and maintain the number of vowels in it. Keep moving the window and update the number of vowels while moving. Answer is max number of vowels of any window.
[Python3] 7-line O(N) time & O(1) space
maximum-length-of-subarray-with-positive-product
0
1
Define two counters `pos` and `neg` as the length of positive and negative products ending at current element. \n\n```\nclass Solution:\n def getMaxLen(self, nums: List[int]) -> int:\n ans = pos = neg = 0\n for x in nums: \n if x > 0: pos, neg = 1 + pos, 1 + neg if neg else 0\n el...
68
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, they can **remove** either the leftmost stone or the rightmost stone from the row and receive points equal to the **sum** of the remaining stones' values in the row. The winner is the ...
Split the whole array into subarrays by zeroes since a subarray with positive product cannot contain any zero. If the subarray has even number of negative numbers, the whole subarray has positive product. Otherwise, we have two choices, either - remove the prefix till the first negative element in this subarray, or rem...
Easy Java Solution 🚀 Clean Code . . .
minimum-number-of-days-to-disconnect-island
1
1
# Java Code\n---\n> #### *Please don\'t forget to upvote if you\'ve liked my solution.* \u2B06\uFE0F\n---\n```\nclass Solution {\n int[] xDir = {0,0,-1,1};\n int[] yDir = {-1,1,0,0};\n public boolean isSafe(int[][] grid,int i,int j,boolean[][] visited)\n {\n return(i>=0 && j>=0 && i<grid.length && j...
6
You are given an `m x n` binary grid `grid` where `1` represents land and `0` represents water. An **island** is a maximal **4-directionally** (horizontal or vertical) connected group of `1`'s. The grid is said to be **connected** if we have **exactly one island**, otherwise is said **disconnected**. In one day, we a...
Note that the node values of a path form a palindrome if at most one digit has an odd frequency (parity). Use a Depth First Search (DFS) keeping the frequency (parity) of the digits. Once you are in a leaf node check if at most one digit has an odd frequency (parity).
python3 solution
minimum-number-of-days-to-disconnect-island
0
1
<!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach : DFS\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(m*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(m*n)\n<!-- Add your space comp...
0
You are given an `m x n` binary grid `grid` where `1` represents land and `0` represents water. An **island** is a maximal **4-directionally** (horizontal or vertical) connected group of `1`'s. The grid is said to be **connected** if we have **exactly one island**, otherwise is said **disconnected**. In one day, we a...
Note that the node values of a path form a palindrome if at most one digit has an odd frequency (parity). Use a Depth First Search (DFS) keeping the frequency (parity) of the digits. Once you are in a leaf node check if at most one digit has an odd frequency (parity).
[Python] Tarjan's Algorithm + Articulation Point detection = at most 2 days of flipping 1s to 0s
minimum-number-of-days-to-disconnect-island
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is a haaaard problem if you don\'t know that we can take at most 2 days to separate a given island. We solve this using SCCs concept + articulation point detection.\n\n# Approach\n<!-- Describe your approach to solving the problem. -...
0
You are given an `m x n` binary grid `grid` where `1` represents land and `0` represents water. An **island** is a maximal **4-directionally** (horizontal or vertical) connected group of `1`'s. The grid is said to be **connected** if we have **exactly one island**, otherwise is said **disconnected**. In one day, we a...
Note that the node values of a path form a palindrome if at most one digit has an odd frequency (parity). Use a Depth First Search (DFS) keeping the frequency (parity) of the digits. Once you are in a leaf node check if at most one digit has an odd frequency (parity).
Not an optimized approach but good to know it.
minimum-number-of-days-to-disconnect-island
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 `m x n` binary grid `grid` where `1` represents land and `0` represents water. An **island** is a maximal **4-directionally** (horizontal or vertical) connected group of `1`'s. The grid is said to be **connected** if we have **exactly one island**, otherwise is said **disconnected**. In one day, we a...
Note that the node values of a path form a palindrome if at most one digit has an odd frequency (parity). Use a Depth First Search (DFS) keeping the frequency (parity) of the digits. Once you are in a leaf node check if at most one digit has an odd frequency (parity).
max 2 days | Easy solution
minimum-number-of-days-to-disconnect-island
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 `m x n` binary grid `grid` where `1` represents land and `0` represents water. An **island** is a maximal **4-directionally** (horizontal or vertical) connected group of `1`'s. The grid is said to be **connected** if we have **exactly one island**, otherwise is said **disconnected**. In one day, we a...
Note that the node values of a path form a palindrome if at most one digit has an odd frequency (parity). Use a Depth First Search (DFS) keeping the frequency (parity) of the digits. Once you are in a leaf node check if at most one digit has an odd frequency (parity).
Python 3 || 9 lines, recursion || T/M: 95% / 80%
number-of-ways-to-reorder-array-to-get-same-bst
0
1
```\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n\n def dp(nums: List[int]) -> int:\n\n n = len(nums)\n if n < 3: return 1\n root, left, right = nums[0], [], []\n\n for x in nums:\n if x < root: left .append(x)\n e...
4
Given an array `nums` that represents a permutation of integers from `1` to `n`. We are going to construct a binary search tree (BST) by inserting the elements of `nums` in order into an initially empty BST. Find the number of different ways to reorder `nums` so that the constructed BST is identical to that formed from...
Use dynamic programming, define DP[i][j] as the maximum dot product of two subsequences starting in the position i of nums1 and position j of nums2.
w Explanation||C++/Python using Math Pascal's triangle/comb Beats 96.74%
number-of-ways-to-reorder-array-to-get-same-bst
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe first element in array must be the root. Then divide the array into left subtree and right subtree! \n\nUse recursion, if the subproblems for left subtree and right subtree are solved, with the returning number l and r, Use the follow...
3
Given an array `nums` that represents a permutation of integers from `1` to `n`. We are going to construct a binary search tree (BST) by inserting the elements of `nums` in order into an initially empty BST. Find the number of different ways to reorder `nums` so that the constructed BST is identical to that formed from...
Use dynamic programming, define DP[i][j] as the maximum dot product of two subsequences starting in the position i of nums1 and position j of nums2.
Python short and clean.
number-of-ways-to-reorder-array-to-get-same-bst
0
1
# Approach\nTL;DR, Similar to [Editorial solution](https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/editorial/).\n\n# Complexity\n- Time complexity: $$O(n ^ 2)$$\n\n- Space complexity: $$O(n ^ 2)$$\n\n# Code\n```python\nclass Solution:\n def numOfWays(self, nums: list[int]) -> int:\n ...
2
Given an array `nums` that represents a permutation of integers from `1` to `n`. We are going to construct a binary search tree (BST) by inserting the elements of `nums` in order into an initially empty BST. Find the number of different ways to reorder `nums` so that the constructed BST is identical to that formed from...
Use dynamic programming, define DP[i][j] as the maximum dot product of two subsequences starting in the position i of nums1 and position j of nums2.
Fastest Solution Yet
number-of-ways-to-reorder-array-to-get-same-bst
0
1
# Intuition\nGiven an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed f...
2
Given an array `nums` that represents a permutation of integers from `1` to `n`. We are going to construct a binary search tree (BST) by inserting the elements of `nums` in order into an initially empty BST. Find the number of different ways to reorder `nums` so that the constructed BST is identical to that formed from...
Use dynamic programming, define DP[i][j] as the maximum dot product of two subsequences starting in the position i of nums1 and position j of nums2.
Best Solution 😎💪🏼
number-of-ways-to-reorder-array-to-get-same-bst
0
1
# Approach\nThe approach used in the code involves a depth-first search (DFS) algorithm. The dfs function takes three parameters: i represents the current index, l represents the lower bound, and h represents the upper bound.\n\nThe function checks if the upper bound h is one greater than the lower bound l. If so, it m...
4
Given an array `nums` that represents a permutation of integers from `1` to `n`. We are going to construct a binary search tree (BST) by inserting the elements of `nums` in order into an initially empty BST. Find the number of different ways to reorder `nums` so that the constructed BST is identical to that formed from...
Use dynamic programming, define DP[i][j] as the maximum dot product of two subsequences starting in the position i of nums1 and position j of nums2.
Python3 Solution
number-of-ways-to-reorder-array-to-get-same-bst
0
1
\n```\nclass Solution:\n def numOfWays(self, nums: List[int]) -> int:\n mod=10**9+7\n \n def f(nums):\n n=len(nums)\n if n<=1:\n return len(nums) \n\n left=[i for i in nums if i<nums[0]]\n right=[i for i in nums if i>nums[0]]\n\n ...
1
Given an array `nums` that represents a permutation of integers from `1` to `n`. We are going to construct a binary search tree (BST) by inserting the elements of `nums` in order into an initially empty BST. Find the number of different ways to reorder `nums` so that the constructed BST is identical to that formed from...
Use dynamic programming, define DP[i][j] as the maximum dot product of two subsequences starting in the position i of nums1 and position j of nums2.
Finding topological sorts (clean code + explanation)
number-of-ways-to-reorder-array-to-get-same-bst
0
1
# Intuition\nThis problem can be rephrased as finding the number of ways to topological sort the BST. We are given one, which can be used to build a tree, and the task is to find the rest.\n\n# Approach\nAfter building our tree, define a helper function `h(x)` that returns the number of topological sortings for the tre...
2
Given an array `nums` that represents a permutation of integers from `1` to `n`. We are going to construct a binary search tree (BST) by inserting the elements of `nums` in order into an initially empty BST. Find the number of different ways to reorder `nums` so that the constructed BST is identical to that formed from...
Use dynamic programming, define DP[i][j] as the maximum dot product of two subsequences starting in the position i of nums1 and position j of nums2.
Python 🐍 Easy & Fast Solution
number-of-ways-to-reorder-array-to-get-same-bst
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nHere are my initial thoughts on how to solve this problem:\n\n- The base case of the recursive function f is when the length of the input list nums is less than or equal to 2, in which case there is only one way to arrange the numbers. ...
63
Given an array `nums` that represents a permutation of integers from `1` to `n`. We are going to construct a binary search tree (BST) by inserting the elements of `nums` in order into an initially empty BST. Find the number of different ways to reorder `nums` so that the constructed BST is identical to that formed from...
Use dynamic programming, define DP[i][j] as the maximum dot product of two subsequences starting in the position i of nums1 and position j of nums2.
Clear Explanation of an Easy Recursive Combinatorics Solution
number-of-ways-to-reorder-array-to-get-same-bst
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs with most tree problems, we repeatedly explore the left and right subtrees of the tree to arrive at our solution. In this case, we look at how many permutations of a subtree array correspond to the same subtree.\n\n# Approach\n<!-- Des...
1
Given an array `nums` that represents a permutation of integers from `1` to `n`. We are going to construct a binary search tree (BST) by inserting the elements of `nums` in order into an initially empty BST. Find the number of different ways to reorder `nums` so that the constructed BST is identical to that formed from...
Use dynamic programming, define DP[i][j] as the maximum dot product of two subsequences starting in the position i of nums1 and position j of nums2.
Python3 Easiest solution || 2 methods
matrix-diagonal-sum
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Simple logic**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- traverse primary diagonal and add elements.\n- while travesing put 0 as diagonal element, indicating we traversed it.\n- now traverse secondary dia...
1
Given a square matrix `mat`, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. **Example 1:** **Input:** mat = \[\[**1**,2,**3**\], \[4,**5**,6\], ...
Use brute force to update a rectangle and, response to the queries in O(1).
Check indices of count of 1. Simple Python implementation
number-of-ways-to-split-a-string
0
1
\n\n# Code\n```\nclass Solution:\n def numWays(self, s: str) -> int:\n MOD = 10 ** 9 + 7\n N = len(s)\n c1 = s.count(\'1\')\n if not c1:\n return (((N-1)*(N-2))//2) % MOD\n if c1 % 3:\n return 0\n idx1, idx2, idx3, idx4 = 0, 0, 0, 0\n cnt = 0\n ...
2
Given a binary string `s`, you can split `s` into 3 **non-empty** strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`. Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Inp...
Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr....
Check indices of count of 1. Simple Python implementation
number-of-ways-to-split-a-string
0
1
\n\n# Code\n```\nclass Solution:\n def numWays(self, s: str) -> int:\n MOD = 10 ** 9 + 7\n N = len(s)\n c1 = s.count(\'1\')\n if not c1:\n return (((N-1)*(N-2))//2) % MOD\n if c1 % 3:\n return 0\n idx1, idx2, idx3, idx4 = 0, 0, 0, 0\n cnt = 0\n ...
2
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concat...
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
[Java/Python 3] Multiplication of the ways of 1st and 2nd cuts w/ explanation and analysis.
number-of-ways-to-split-a-string
1
1
Please refer to the outstanding elaboration from `@lionkingeatapple`, who deserves more upvotes than me:\n\n----\n\nWe have three different scenarios.\n\n`scenarios_1:` If the total number of ones in the input string is not the multiple of three, there is no way we can cut the string into three blocks with an equal num...
205
Given a binary string `s`, you can split `s` into 3 **non-empty** strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`. Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Inp...
Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr....
[Java/Python 3] Multiplication of the ways of 1st and 2nd cuts w/ explanation and analysis.
number-of-ways-to-split-a-string
1
1
Please refer to the outstanding elaboration from `@lionkingeatapple`, who deserves more upvotes than me:\n\n----\n\nWe have three different scenarios.\n\n`scenarios_1:` If the total number of ones in the input string is not the multiple of three, there is no way we can cut the string into three blocks with an equal num...
205
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concat...
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
Python | One-pass | Explained & Visualised
number-of-ways-to-split-a-string
0
1
Scan ```s``` to record positions for ```\'1\'```. After checking the edge cases, the result is simply a combination of choices.\n![image](https://assets.leetcode.com/users/images/18f66338-ce4e-4667-a750-549ff019d9a2_1599323828.9086614.png)\n\n```Python\nclass Solution:\n def numWays(self, s: str) -> int:\n n,...
87
Given a binary string `s`, you can split `s` into 3 **non-empty** strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`. Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Inp...
Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr....
Python | One-pass | Explained & Visualised
number-of-ways-to-split-a-string
0
1
Scan ```s``` to record positions for ```\'1\'```. After checking the edge cases, the result is simply a combination of choices.\n![image](https://assets.leetcode.com/users/images/18f66338-ce4e-4667-a750-549ff019d9a2_1599323828.9086614.png)\n\n```Python\nclass Solution:\n def numWays(self, s: str) -> int:\n n,...
87
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concat...
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
Python | Combination concept Mathematics | Explained with Concept and Code | Easy Solution
number-of-ways-to-split-a-string
0
1
<h1>There are two most important part of the solution</h1>\n\n### Basic Observation\n- The only part that matters are zeroes that lies on the borders\n- Borders are the places from where the string is split, it is **2** here\n### 1. When there are only zeroes\n- Let\'s us understand this in terms of following details\n...
22
Given a binary string `s`, you can split `s` into 3 **non-empty** strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`. Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Inp...
Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr....
Python | Combination concept Mathematics | Explained with Concept and Code | Easy Solution
number-of-ways-to-split-a-string
0
1
<h1>There are two most important part of the solution</h1>\n\n### Basic Observation\n- The only part that matters are zeroes that lies on the borders\n- Borders are the places from where the string is split, it is **2** here\n### 1. When there are only zeroes\n- Let\'s us understand this in terms of following details\n...
22
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concat...
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
Python O(n) + Explanation
number-of-ways-to-split-a-string
0
1
First count 1\'s in given string. ```cnt = s.count(\'1\')```\n**if cnt == 0:** special case: ```return (len(s)-1)*(len(s)-2)//2```\n**elif cnt is not divisible by 3:** ```return 0```\n**else:**\nkeep track of indices of 1\'s in ones list:\nfor exaple: s = \'100100010100110\'\nones = [0,3,7,9,12,13]\nwe need to devide t...
13
Given a binary string `s`, you can split `s` into 3 **non-empty** strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`. Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Inp...
Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr....
Python O(n) + Explanation
number-of-ways-to-split-a-string
0
1
First count 1\'s in given string. ```cnt = s.count(\'1\')```\n**if cnt == 0:** special case: ```return (len(s)-1)*(len(s)-2)//2```\n**elif cnt is not divisible by 3:** ```return 0```\n**else:**\nkeep track of indices of 1\'s in ones list:\nfor exaple: s = \'100100010100110\'\nones = [0,3,7,9,12,13]\nwe need to devide t...
13
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concat...
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
Permutation solution
number-of-ways-to-split-a-string
0
1
# Intuition\nSplit the string into 3 piece, in other words, need to selet two position r index to cut over \n\n# Approach\nuse index_1, index_2, index_3, index_4 to mark the two position\'s range\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def numWays(sel...
0
Given a binary string `s`, you can split `s` into 3 **non-empty** strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`. Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Inp...
Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr....
Permutation solution
number-of-ways-to-split-a-string
0
1
# Intuition\nSplit the string into 3 piece, in other words, need to selet two position r index to cut over \n\n# Approach\nuse index_1, index_2, index_3, index_4 to mark the two position\'s range\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def numWays(sel...
0
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concat...
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
Trash problem
number-of-ways-to-split-a-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given a binary string `s`, you can split `s` into 3 **non-empty** strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`. Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Inp...
Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr....
Trash problem
number-of-ways-to-split-a-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concat...
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
Probably the easiest and most intuitive method one can come up with with O(n) time and O(1) space
number-of-ways-to-split-a-string
0
1
# Intuition\nwe start by creating boundaries i imagined them as blocks \nhow many ways can one can create three seprations that is going to be\nto cut it from 2 different places \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n...
0
Given a binary string `s`, you can split `s` into 3 **non-empty** strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`. Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Inp...
Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr....
Probably the easiest and most intuitive method one can come up with with O(n) time and O(1) space
number-of-ways-to-split-a-string
0
1
# Intuition\nwe start by creating boundaries i imagined them as blocks \nhow many ways can one can create three seprations that is going to be\nto cut it from 2 different places \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n...
0
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concat...
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
Python3 | O(n) Time complexity | Two pointers
shortest-subarray-to-be-removed-to-make-array-sorted
0
1
Cases:\n1. Remove left side:\n\t- eg. nums = [5,1, 3, 6] -> Remove nums[0:1] = [5]\n2. Remove right side:\n\t- eg. nums = [5, 6, 1, 0] -> Remove nums[2:] = [1, 0]\n3. Remove middle:\n - eg. nums = [1, 2, 3, 6, 4, 5] -> Remove nums[3:4] = [6]\n4. Remove nothing:\n\t- eg. nums = [1,2,3] -> Remove nothing\n```\nclass S...
6
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
Python3 | O(n) Time complexity | Two pointers
shortest-subarray-to-be-removed-to-make-array-sorted
0
1
Cases:\n1. Remove left side:\n\t- eg. nums = [5,1, 3, 6] -> Remove nums[0:1] = [5]\n2. Remove right side:\n\t- eg. nums = [5, 6, 1, 0] -> Remove nums[2:] = [1, 0]\n3. Remove middle:\n - eg. nums = [1, 2, 3, 6, 4, 5] -> Remove nums[3:4] = [6]\n4. Remove nothing:\n\t- eg. nums = [1,2,3] -> Remove nothing\n```\nclass S...
6
You are given an integer array `nums` and an integer `k`. In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array. Return _the maximum number of operations you can perform on the array_. **Example 1:** **Input:** nums = \[1,2,3,4\], k = 5 **Output:** 2 **Explana...
The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively. After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix...
Break the array and binary search
shortest-subarray-to-be-removed-to-make-array-sorted
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nfind the left part and right part that is non-decreasing.\nFor each value `arr[i]` in left part, find the first value in right part >= `arr[i]`\nFor each value `arr[i]` in right part, find the last value in left part <= `arr[i]`\n\n# Comp...
1
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
Break the array and binary search
shortest-subarray-to-be-removed-to-make-array-sorted
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nfind the left part and right part that is non-decreasing.\nFor each value `arr[i]` in left part, find the first value in right part >= `arr[i]`\nFor each value `arr[i]` in right part, find the last value in left part <= `arr[i]`\n\n# Comp...
1
You are given an integer array `nums` and an integer `k`. In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array. Return _the maximum number of operations you can perform on the array_. **Example 1:** **Input:** nums = \[1,2,3,4\], k = 5 **Output:** 2 **Explana...
The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively. After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix...
Beats 96.93% || Basic Two Pointer Approach
shortest-subarray-to-be-removed-to-make-array-sorted
0
1
# Intuition\nWhen I saw that the constraints are of the range 10^5, I decided to use a Two Pointer approach.Then I thought that if it is a subarray it should be increasing that means of we remove some elements from middle, then definitely the first subarray should be increasing and the second subarray should be increas...
0
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
Beats 96.93% || Basic Two Pointer Approach
shortest-subarray-to-be-removed-to-make-array-sorted
0
1
# Intuition\nWhen I saw that the constraints are of the range 10^5, I decided to use a Two Pointer approach.Then I thought that if it is a subarray it should be increasing that means of we remove some elements from middle, then definitely the first subarray should be increasing and the second subarray should be increas...
0
You are given an integer array `nums` and an integer `k`. In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array. Return _the maximum number of operations you can perform on the array_. **Example 1:** **Input:** nums = \[1,2,3,4\], k = 5 **Output:** 2 **Explana...
The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively. After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix...
Python Simple linear time Solution
shortest-subarray-to-be-removed-to-make-array-sorted
0
1
# Intuition\nThe question asks us to make the array sorted by removing a subarray. So we can boil down the solution to three steps :-\n\n1. Find the non decreasing subarray from start=0 and remove all part of array after that.\n1. Find the non increasing subarray from end=len(arr)-1 and remove all part of the array bef...
0
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
Python Simple linear time Solution
shortest-subarray-to-be-removed-to-make-array-sorted
0
1
# Intuition\nThe question asks us to make the array sorted by removing a subarray. So we can boil down the solution to three steps :-\n\n1. Find the non decreasing subarray from start=0 and remove all part of array after that.\n1. Find the non increasing subarray from end=len(arr)-1 and remove all part of the array bef...
0
You are given an integer array `nums` and an integer `k`. In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array. Return _the maximum number of operations you can perform on the array_. **Example 1:** **Input:** nums = \[1,2,3,4\], k = 5 **Output:** 2 **Explana...
The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively. After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix...
easy C++/Python dfs DP solutions
count-all-possible-routes
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse DFS and DP. Set dp[i][fuel] as the state for the city i and with fuel=fuel.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe given code counts the number of routes from a start to a finish location within a fu...
4
You are given an array of **distinct** positive integers locations where `locations[i]` represents the position of city `i`. You are also given integers `start`, `finish` and `fuel` representing the starting city, ending city, and the initial amount of fuel you have, respectively. At each step, if you are at city `i`,...
Sort the arrays, then compute the maximum difference between two consecutive elements for horizontal cuts and vertical cuts. The answer is the product of these maximum values in horizontal cuts and vertical cuts.
easy C++/Python dfs DP solutions
count-all-possible-routes
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse DFS and DP. Set dp[i][fuel] as the state for the city i and with fuel=fuel.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe given code counts the number of routes from a start to a finish location within a fu...
4
Given an integer `n`, return _the **decimal value** of the binary string formed by concatenating the binary representations of_ `1` _to_ `n` _in order, **modulo**_ `109 + 7`. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation: ** "1 " in binary corresponds to the decimal value 1. **Example 2:** **Input:**...
Use dynamic programming to solve this problem with each state defined by the city index and fuel left. Since the array contains distinct integers fuel will always be spent in each move and so there can be no cycles.