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
[C++/Java/Python]- Easy One liner with explanation
partitioning-into-minimum-number-of-deci-binary-numbers
1
1
For this one, we would just rely on simple maths.\n> Example: **n = "153"**\n> \nNow let\'s break down each digit with required number of ones as we can use only `0` or `1` in deci-binaries.\n>**1** - 1 0 0 0 0 \n>**5** - 1 1 1 1 1\n>**3** - 1 1 1 0 0 \n> Added zero padding to the tail to align with max number of ...
70
You are given a string `s` that contains some bracket pairs, with each pair containing a **non-empty** key. * For example, in the string `"(name)is(age)yearsold "`, there are **two** bracket pairs that contain the keys `"name "` and `"age "`. You know the values of a wide range of keys. This is represented by a 2D ...
Think about if the input was only one digit. Then you need to add up as many ones as the value of this digit. If the input has multiple digits, then you can solve for each digit independently, and merge the answers to form numbers that add up to that input. Thus the answer is equal to the max digit.
Detailed Easiest Explanation of Solution
partitioning-into-minimum-number-of-deci-binary-numbers
0
1
I was trying it hard for several days , then checked out the discussion group for some hints.\nI really got surprised by the one-liner solutions. I\'m just providing here the detailed explanation to the solution for others to get help from it.\n\n**In Python**\n```\nclass Solution:\n def minPartitions(self, n: str) ...
149
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.
Detailed Easiest Explanation of Solution
partitioning-into-minimum-number-of-deci-binary-numbers
0
1
I was trying it hard for several days , then checked out the discussion group for some hints.\nI really got surprised by the one-liner solutions. I\'m just providing here the detailed explanation to the solution for others to get help from it.\n\n**In Python**\n```\nclass Solution:\n def minPartitions(self, n: str) ...
149
You are given a string `s` that contains some bracket pairs, with each pair containing a **non-empty** key. * For example, in the string `"(name)is(age)yearsold "`, there are **two** bracket pairs that contain the keys `"name "` and `"age "`. You know the values of a wide range of keys. This is represented by a 2D ...
Think about if the input was only one digit. Then you need to add up as many ones as the value of this digit. If the input has multiple digits, then you can solve for each digit independently, and merge the answers to form numbers that add up to that input. Thus the answer is equal to the max digit.
Python3 easy solution
partitioning-into-minimum-number-of-deci-binary-numbers
0
1
# Complexity\n- Time complexity: $$O(n)$$, where n is the length of the input string n.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minPartitions(self, n: str) -> int:\n ret...
2
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 easy solution
partitioning-into-minimum-number-of-deci-binary-numbers
0
1
# Complexity\n- Time complexity: $$O(n)$$, where n is the length of the input string n.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minPartitions(self, n: str) -> int:\n ret...
2
You are given a string `s` that contains some bracket pairs, with each pair containing a **non-empty** key. * For example, in the string `"(name)is(age)yearsold "`, there are **two** bracket pairs that contain the keys `"name "` and `"age "`. You know the values of a wide range of keys. This is represented by a 2D ...
Think about if the input was only one digit. Then you need to add up as many ones as the value of this digit. If the input has multiple digits, then you can solve for each digit independently, and merge the answers to form numbers that add up to that input. Thus the answer is equal to the max digit.
Beginner-friendly || Simple/tricky solution in Python3 and JavaScript/TypeScript
partitioning-into-minimum-number-of-deci-binary-numbers
0
1
# Intuition\nThe problem description is the following:\n- there\'s a `n` string, that\'s a valid positive integer\n- our goal is to calculate, how many **deci-binary** integers it contains \n\nFollowing to the statement, **deci-binary** integer is that, which has only `1`-s and `0`-s as digits with **no leading zeroes*...
2
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.
Beginner-friendly || Simple/tricky solution in Python3 and JavaScript/TypeScript
partitioning-into-minimum-number-of-deci-binary-numbers
0
1
# Intuition\nThe problem description is the following:\n- there\'s a `n` string, that\'s a valid positive integer\n- our goal is to calculate, how many **deci-binary** integers it contains \n\nFollowing to the statement, **deci-binary** integer is that, which has only `1`-s and `0`-s as digits with **no leading zeroes*...
2
You are given a string `s` that contains some bracket pairs, with each pair containing a **non-empty** key. * For example, in the string `"(name)is(age)yearsold "`, there are **two** bracket pairs that contain the keys `"name "` and `"age "`. You know the values of a wide range of keys. This is represented by a 2D ...
Think about if the input was only one digit. Then you need to add up as many ones as the value of this digit. If the input has multiple digits, then you can solve for each digit independently, and merge the answers to form numbers that add up to that input. Thus the answer is equal to the max digit.
Python3 || Beats 91.67% 🚀🚀|| One liner || Self explanatory.
partitioning-into-minimum-number-of-deci-binary-numbers
0
1
# **Note:**\n**Check the hint given in description to understand the solution.**\n# Code\n```\nclass Solution:\n def minPartitions(self, n: str) -> int:\n return int(max(n)) \n```\n**Please upvote if you find it helpful.**
4
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 || Beats 91.67% 🚀🚀|| One liner || Self explanatory.
partitioning-into-minimum-number-of-deci-binary-numbers
0
1
# **Note:**\n**Check the hint given in description to understand the solution.**\n# Code\n```\nclass Solution:\n def minPartitions(self, n: str) -> int:\n return int(max(n)) \n```\n**Please upvote if you find it helpful.**
4
You are given a string `s` that contains some bracket pairs, with each pair containing a **non-empty** key. * For example, in the string `"(name)is(age)yearsold "`, there are **two** bracket pairs that contain the keys `"name "` and `"age "`. You know the values of a wide range of keys. This is represented by a 2D ...
Think about if the input was only one digit. Then you need to add up as many ones as the value of this digit. If the input has multiple digits, then you can solve for each digit independently, and merge the answers to form numbers that add up to that input. Thus the answer is equal to the max digit.
Python - one line code
partitioning-into-minimum-number-of-deci-binary-numbers
0
1
```\nclass Solution:\n def minPartitions(self, n: str) -> int:\n return max(n)\n```
2
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 code
partitioning-into-minimum-number-of-deci-binary-numbers
0
1
```\nclass Solution:\n def minPartitions(self, n: str) -> int:\n return max(n)\n```
2
You are given a string `s` that contains some bracket pairs, with each pair containing a **non-empty** key. * For example, in the string `"(name)is(age)yearsold "`, there are **two** bracket pairs that contain the keys `"name "` and `"age "`. You know the values of a wide range of keys. This is represented by a 2D ...
Think about if the input was only one digit. Then you need to add up as many ones as the value of this digit. If the input has multiple digits, then you can solve for each digit independently, and merge the answers to form numbers that add up to that input. Thus the answer is equal to the max digit.
Python3 || Can't believe this solution || 99 % Faster 🚀
partitioning-into-minimum-number-of-deci-binary-numbers
0
1
**Upvote and let others also see \uD83D\uDE02\uD83D\uDC4C\u2764\uFE0F**\n.\n\n* By observation we can say we only have deci-binary (0, 1) to sum up to given number n, we need atleast n[i] deci-binary numbers to sum up to n[i], where n[i] is the ith digit of given number.\n\n* Consider n="9", We need to add 1 for 9 ti...
4
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 || Can't believe this solution || 99 % Faster 🚀
partitioning-into-minimum-number-of-deci-binary-numbers
0
1
**Upvote and let others also see \uD83D\uDE02\uD83D\uDC4C\u2764\uFE0F**\n.\n\n* By observation we can say we only have deci-binary (0, 1) to sum up to given number n, we need atleast n[i] deci-binary numbers to sum up to n[i], where n[i] is the ith digit of given number.\n\n* Consider n="9", We need to add 1 for 9 ti...
4
You are given a string `s` that contains some bracket pairs, with each pair containing a **non-empty** key. * For example, in the string `"(name)is(age)yearsold "`, there are **two** bracket pairs that contain the keys `"name "` and `"age "`. You know the values of a wide range of keys. This is represented by a 2D ...
Think about if the input was only one digit. Then you need to add up as many ones as the value of this digit. If the input has multiple digits, then you can solve for each digit independently, and merge the answers to form numbers that add up to that input. Thus the answer is equal to the max digit.
Python 3 || 5 lines, recursion, prefix || T/M: 59% / 88%
stone-game-vii
0
1
I had trouble with TLE, even with `@lru_cache(None)`. Someone under the Discussion tab said resetting it to `2000` would help, and it did!\n```\nclass Solution:\n def stoneGameVII(self, stones: List[int]) -> int:\n\n pref = list(accumulate(stones, initial = 0))\n \n @lru_cache(2000)\n def...
3
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...
Python 3 || 5 lines, recursion, prefix || T/M: 59% / 88%
stone-game-vii
0
1
I had trouble with TLE, even with `@lru_cache(None)`. Someone under the Discussion tab said resetting it to `2000` would help, and it did!\n```\nclass Solution:\n def stoneGameVII(self, stones: List[int]) -> int:\n\n pref = list(accumulate(stones, initial = 0))\n \n @lru_cache(2000)\n def...
3
You are given a positive integer `primeFactors`. You are asked to construct a positive integer `n` that satisfies the following conditions: * The number of prime factors of `n` (not necessarily distinct) is **at most** `primeFactors`. * The number of nice divisors of `n` is maximized. Note that a divisor of `n` is...
The constraints are small enough for an N^2 solution. Try using dynamic programming.
Time 100% and Memory 100%
stone-game-vii
0
1
# Intuition\nNotice that the difference of scores is the sum of all the stones that Bob takes, so for both Alice and Bob, their optimal strategy is to minimize their own sums of stones.\n\n# Approach\nUse dynamic programming from the last step to the first.\n\n# Complexity\n- Time complexity:\n$O(n^2)$\n\n- Space compl...
1
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, 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...
Time 100% and Memory 100%
stone-game-vii
0
1
# Intuition\nNotice that the difference of scores is the sum of all the stones that Bob takes, so for both Alice and Bob, their optimal strategy is to minimize their own sums of stones.\n\n# Approach\nUse dynamic programming from the last step to the first.\n\n# Complexity\n- Time complexity:\n$O(n^2)$\n\n- Space compl...
1
You are given a positive integer `primeFactors`. You are asked to construct a positive integer `n` that satisfies the following conditions: * The number of prime factors of `n` (not necessarily distinct) is **at most** `primeFactors`. * The number of nice divisors of `n` is maximized. Note that a divisor of `n` is...
The constraints are small enough for an N^2 solution. Try using dynamic programming.
Recursion->Memoization->Tabulation
stone-game-vii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n```\nAlice Turn\n [5 3 1 4 2]\n A = 5 + 3 + 1 + 4 = 13 \nBob Turn\n [5 3 1 4]\n B = 3 + 1 + 4 = 8\nAlice Turn\n [3 1 4]\n A = 1 + 4 = 5\nBob Turn\n [1 4]\n B = 4 = 4\nResult\n ...
3
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...
Recursion->Memoization->Tabulation
stone-game-vii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n```\nAlice Turn\n [5 3 1 4 2]\n A = 5 + 3 + 1 + 4 = 13 \nBob Turn\n [5 3 1 4]\n B = 3 + 1 + 4 = 8\nAlice Turn\n [3 1 4]\n A = 1 + 4 = 5\nBob Turn\n [1 4]\n B = 4 = 4\nResult\n ...
3
You are given a positive integer `primeFactors`. You are asked to construct a positive integer `n` that satisfies the following conditions: * The number of prime factors of `n` (not necessarily distinct) is **at most** `primeFactors`. * The number of nice divisors of `n` is maximized. Note that a divisor of `n` is...
The constraints are small enough for an N^2 solution. Try using dynamic programming.
[Python3] Easy code with explanation - DP
stone-game-vii
0
1
The subproblem for the DP solution is that,\nFor n = 1, Alice or Bob picks the stone and nobody gets any score.\nFor n = 2, the person picks first stone and the score equals second stone or vice versa.\nso on....\n\nNow, that we have the subproblem how do we fill the DP table and fill it with what?\nI thought of 3 choi...
9
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] Easy code with explanation - DP
stone-game-vii
0
1
The subproblem for the DP solution is that,\nFor n = 1, Alice or Bob picks the stone and nobody gets any score.\nFor n = 2, the person picks first stone and the score equals second stone or vice versa.\nso on....\n\nNow, that we have the subproblem how do we fill the DP table and fill it with what?\nI thought of 3 choi...
9
You are given a positive integer `primeFactors`. You are asked to construct a positive integer `n` that satisfies the following conditions: * The number of prime factors of `n` (not necessarily distinct) is **at most** `primeFactors`. * The number of nice divisors of `n` is maximized. Note that a divisor of `n` is...
The constraints are small enough for an N^2 solution. Try using dynamic programming.
Python3, O(n*n) time O(n) space, bottom-up DP, no prefix, beats 97%
stone-game-vii
0
1
# Intuition\nThe intuition behind this solution is that the difference in scores between Alice and Bob is actually the sum of the values of the stones removed by Bob. This can be seen by considering each Alice + Bob turn in isolation (if the number of stones is odd, the last turn where only Alice removes a stone does n...
0
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, 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, O(n*n) time O(n) space, bottom-up DP, no prefix, beats 97%
stone-game-vii
0
1
# Intuition\nThe intuition behind this solution is that the difference in scores between Alice and Bob is actually the sum of the values of the stones removed by Bob. This can be seen by considering each Alice + Bob turn in isolation (if the number of stones is odd, the last turn where only Alice removes a stone does n...
0
You are given a positive integer `primeFactors`. You are asked to construct a positive integer `n` that satisfies the following conditions: * The number of prime factors of `n` (not necessarily distinct) is **at most** `primeFactors`. * The number of nice divisors of `n` is maximized. Note that a divisor of `n` is...
The constraints are small enough for an N^2 solution. Try using dynamic programming.
[Python] compact solution
stone-game-vii
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n`c` is partial sum of original array `s` which gives us sum of points in an interval on `s`. In every turn, a player has two options which are pick the stone on the left `l` or on the right `r`. We should return `max` of these options. If there is one...
0
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, 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...
[Python] compact solution
stone-game-vii
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n`c` is partial sum of original array `s` which gives us sum of points in an interval on `s`. In every turn, a player has two options which are pick the stone on the left `l` or on the right `r`. We should return `max` of these options. If there is one...
0
You are given a positive integer `primeFactors`. You are asked to construct a positive integer `n` that satisfies the following conditions: * The number of prime factors of `n` (not necessarily distinct) is **at most** `primeFactors`. * The number of nice divisors of `n` is maximized. Note that a divisor of `n` is...
The constraints are small enough for an N^2 solution. Try using dynamic programming.
python with clean explanation with example(dp with sort)
maximum-height-by-stacking-cuboids
0
1
**a brief explanation on how code works:**\n consider example: [[50,45,20],[95,37,53],[45,23,12]]\n* at first we are assigning length of cubiods list to n (=3)\n* initializing dp arrray with 0 values of length n \n\t\t\t\t\t\tdp[3] = [0, 0, 0]\n* we are sorting the inner lists in order to get maximum height s...
0
Given a binary tree `root` and a linked list with `head` as the first node. Return True if all the elements in the linked list starting from the `head` correspond to some _downward path_ connected in the binary tree otherwise return False. In this context downward path means a path that starts at some node and goes d...
Does the dynamic programming sound like the right algorithm after sorting? Let's say box1 can be placed on top of box2. No matter what orientation box2 is in, we can rotate box1 so that it can be placed on top. Why don't we orient everything such that height is the biggest?
python with clean explanation with example(dp with sort)
maximum-height-by-stacking-cuboids
0
1
**a brief explanation on how code works:**\n consider example: [[50,45,20],[95,37,53],[45,23,12]]\n* at first we are assigning length of cubiods list to n (=3)\n* initializing dp arrray with 0 values of length n \n\t\t\t\t\t\tdp[3] = [0, 0, 0]\n* we are sorting the inner lists in order to get maximum height s...
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 are allowed to change any single ...
Return 0 if the grid is already disconnected. Return 1 if changing a single land to water disconnect the island. Otherwise return 2. We can disconnect the grid within at most 2 days.
Python 3 | DP, Sort, O(N^2) | Explanation
maximum-height-by-stacking-cuboids
0
1
### Explanation\n- Sort each cub\'s length, width, height from small to large\n- Sort cub by length, width, height from large to small\n- Initialize a 1-D dp array, `dp[i] = largest height if put cuboids[i] at the top`\n- Iterate over cuboids, from large to small; try get the largest height by putting itself on previou...
7
Given a binary tree `root` and a linked list with `head` as the first node. Return True if all the elements in the linked list starting from the `head` correspond to some _downward path_ connected in the binary tree otherwise return False. In this context downward path means a path that starts at some node and goes d...
Does the dynamic programming sound like the right algorithm after sorting? Let's say box1 can be placed on top of box2. No matter what orientation box2 is in, we can rotate box1 so that it can be placed on top. Why don't we orient everything such that height is the biggest?
Python 3 | DP, Sort, O(N^2) | Explanation
maximum-height-by-stacking-cuboids
0
1
### Explanation\n- Sort each cub\'s length, width, height from small to large\n- Sort cub by length, width, height from large to small\n- Initialize a 1-D dp array, `dp[i] = largest height if put cuboids[i] at the top`\n- Iterate over cuboids, from large to small; try get the largest height by putting itself on previou...
7
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 are allowed to change any single ...
Return 0 if the grid is already disconnected. Return 1 if changing a single land to water disconnect the island. Otherwise return 2. We can disconnect the grid within at most 2 days.
Pandas vs SQL | Elegant & Short | All 30 Days of Pandas solutions ✅
daily-leads-and-partners
0
1
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```Python []\ndef daily_leads_and_partners(daily_sales: pd.DataFrame) -> pd.DataFrame:\n return daily_sales.groupby(\n [\'date_id\', \'make_name\']\n ).nunique().reset_index().rename(columns={\n \'lead_id\': \'unique_...
20
Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`. After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`. **Example 1:** **Input:** n = 34, k = 6 **Out...
null
✅ Pandas Simple Step By Step Solution For Beginners 🔥💯
daily-leads-and-partners
0
1
**\uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n```\nimport pandas as pd\n\ndef daily_leads_and_partners(daily_sales: pd.DataFrame) -> pd.DataFrame:\n \n result = daily_sales.groupby([\'date_id\', \'make_name\']).nunique().reset_index()\n \n result.columns = [\'date_id\', \'make_n...
2
Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`. After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`. **Example 1:** **Input:** n = 34, k = 6 **Out...
null
Beginer Friendly solution Python3 Beat 92% O(n)
reformat-phone-number
0
1
\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def reformatNumber(self, number: str) -> str:\n number, a, i = (number.replace(\' \', \'\').rep...
1
You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`. You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or f...
Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost i...
Beginer Friendly solution Python3 Beat 92% O(n)
reformat-phone-number
0
1
\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def reformatNumber(self, number: str) -> str:\n number, a, i = (number.replace(\' \', \'\').rep...
1
You are given `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return `true` _if the square is white, and_ `false` _if the square is black_. The coordinate will always represent a valid chessboard square. The coordinate will always have t...
Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply.
Python Easy to Understand
reformat-phone-number
0
1
# Code\n```\nclass Solution:\n def reformatNumber(self, number: str) -> str:\n res=[]\n new=""\n for i in number:\n if i!=" " and i!="-":\n res.append(i)\n n=len(res)\n while(n>4):\n s="".join(res[:3])\n res=res[3:]\n n-=3\...
1
You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`. You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or f...
Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost i...
Python Easy to Understand
reformat-phone-number
0
1
# Code\n```\nclass Solution:\n def reformatNumber(self, number: str) -> str:\n res=[]\n new=""\n for i in number:\n if i!=" " and i!="-":\n res.append(i)\n n=len(res)\n while(n>4):\n s="".join(res[:3])\n res=res[3:]\n n-=3\...
1
You are given `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return `true` _if the square is white, and_ `false` _if the square is black_. The coordinate will always represent a valid chessboard square. The coordinate will always have t...
Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply.
Simple and Easy Python Code
reformat-phone-number
0
1
\n\n# Complexity\n- Time complexity:\nO(n)\n\n\n# Code\n```\nclass Solution:\n def reformatNumber(self, number: str) -> str:\n number = number.strip()\n no=\'\'\n\n for i in number:\n if i>=chr(48) and i <=chr(57):\n no=no+i\n \n number=no\n l,i = len(n...
2
You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`. You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or f...
Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost i...
Simple and Easy Python Code
reformat-phone-number
0
1
\n\n# Complexity\n- Time complexity:\nO(n)\n\n\n# Code\n```\nclass Solution:\n def reformatNumber(self, number: str) -> str:\n number = number.strip()\n no=\'\'\n\n for i in number:\n if i>=chr(48) and i <=chr(57):\n no=no+i\n \n number=no\n l,i = len(n...
2
You are given `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return `true` _if the square is white, and_ `false` _if the square is black_. The coordinate will always represent a valid chessboard square. The coordinate will always have t...
Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply.
[Python3] string processing
reformat-phone-number
0
1
**Algo**\nCheck the special case of 4 letters remaining. \n\n**Implementation**\n```\nclass Solution:\n def reformatNumber(self, number: str) -> str:\n number = number.replace("-", "").replace(" ", "") # removing - and space \n ans = []\n for i in range(0, len(number), 3): \n if len(n...
18
You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`. You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or f...
Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost i...
[Python3] string processing
reformat-phone-number
0
1
**Algo**\nCheck the special case of 4 letters remaining. \n\n**Implementation**\n```\nclass Solution:\n def reformatNumber(self, number: str) -> str:\n number = number.replace("-", "").replace(" ", "") # removing - and space \n ans = []\n for i in range(0, len(number), 3): \n if len(n...
18
You are given `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return `true` _if the square is white, and_ `false` _if the square is black_. The coordinate will always represent a valid chessboard square. The coordinate will always have t...
Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply.
O(n) in Python
reformat-phone-number
0
1
# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def reformatNumber(self, number: str) -> str:\n num = number.replace(\' \', \'\').replace(\'-\', \'...
1
You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`. You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or f...
Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost i...
O(n) in Python
reformat-phone-number
0
1
# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def reformatNumber(self, number: str) -> str:\n num = number.replace(\' \', \'\').replace(\'-\', \'...
1
You are given `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return `true` _if the square is white, and_ `false` _if the square is black_. The coordinate will always represent a valid chessboard square. The coordinate will always have t...
Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply.
Python Solution using Minimal New Variables (+ Explanation for Logic)
reformat-phone-number
0
1
My first attempt at this problem utilized separating the string into an array and while that works, it\'s clearly not the intended solution. This function instead works by overwriting the existing string input and outputting the necessary values into another string to be returned. Leetcode keeps flip-flopping on just h...
2
You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`. You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or f...
Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost i...
Python Solution using Minimal New Variables (+ Explanation for Logic)
reformat-phone-number
0
1
My first attempt at this problem utilized separating the string into an array and while that works, it\'s clearly not the intended solution. This function instead works by overwriting the existing string input and outputting the necessary values into another string to be returned. Leetcode keeps flip-flopping on just h...
2
You are given `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return `true` _if the square is white, and_ `false` _if the square is black_. The coordinate will always represent a valid chessboard square. The coordinate will always have t...
Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply.
Python Solution Easy To Read!!
reformat-phone-number
0
1
\n# Code\n```\nclass Solution:\n def reformatNumber(self, number: str) -> str:\n \n number = number.replace(" ","").replace("-","")\n phone: list = [number[index: index + 3] for index in range(0, len(number), 3)] \n \n if len(phone[-1]) == 1:\n phone[-2:] = [phone[-2][:-1], phone...
0
You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`. You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or f...
Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost i...
Python Solution Easy To Read!!
reformat-phone-number
0
1
\n# Code\n```\nclass Solution:\n def reformatNumber(self, number: str) -> str:\n \n number = number.replace(" ","").replace("-","")\n phone: list = [number[index: index + 3] for index in range(0, len(number), 3)] \n \n if len(phone[-1]) == 1:\n phone[-2:] = [phone[-2][:-1], phone...
0
You are given `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return `true` _if the square is white, and_ `false` _if the square is black_. The coordinate will always represent a valid chessboard square. The coordinate will always have t...
Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply.
Python solution
reformat-phone-number
0
1
```\nclass Solution:\n def reformatNumber(self, number: str) -> str:\n numbers: str = "".join([number for number in number if number not in [" ", "-"]])\n packages: list[str] = []\n\n for i in range(0, len(numbers), 3):\n packages.append(numbers[i: i + 3])\n\n if len(packages[-...
0
You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`. You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or f...
Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost i...
Python solution
reformat-phone-number
0
1
```\nclass Solution:\n def reformatNumber(self, number: str) -> str:\n numbers: str = "".join([number for number in number if number not in [" ", "-"]])\n packages: list[str] = []\n\n for i in range(0, len(numbers), 3):\n packages.append(numbers[i: i + 3])\n\n if len(packages[-...
0
You are given `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return `true` _if the square is white, and_ `false` _if the square is black_. The coordinate will always represent a valid chessboard square. The coordinate will always have t...
Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply.
Python3 Solution
reformat-phone-number
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given a phone number as a string `number`. `number` consists of digits, spaces `' '`, and/or dashes `'-'`. You would like to reformat the phone number in a certain manner. Firstly, **remove** all spaces and dashes. Then, **group** the digits from left to right into blocks of length 3 **until** there are 4 or f...
Use prefix sums to calculate the subarray sums. Suppose you know the remainder for the sum of the entire array. How does removing a subarray affect that remainder? What remainder does the subarray need to have in order to make the rest of the array sum up to be divisible by k? Use a map to keep track of the rightmost i...
Python3 Solution
reformat-phone-number
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 `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return `true` _if the square is white, and_ `false` _if the square is black_. The coordinate will always represent a valid chessboard square. The coordinate will always have t...
Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply.
✅ Python Easy 2 approaches
maximum-erasure-value
0
1
## \u2714\uFE0F*Solution I - Two pointers using Counter*\n```\nclass Solution:\n def maximumUniqueSubarray(self, nums: List[int]) -> int:\n counter=defaultdict(int) # track count of elements in the window\n res=i=tot=0\n\t\t\n for j in range(len(nums)):\n x=nums[j] \n to...
18
You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements. Return _the **maximum score** you can get by erasing **exactly one** subarray._ An array `b` is called to be a subarray...
Indexes with higher frequencies should be bound with larger values
✅ Python Easy 2 approaches
maximum-erasure-value
0
1
## \u2714\uFE0F*Solution I - Two pointers using Counter*\n```\nclass Solution:\n def maximumUniqueSubarray(self, nums: List[int]) -> int:\n counter=defaultdict(int) # track count of elements in the window\n res=i=tot=0\n\t\t\n for j in range(len(nums)):\n x=nums[j] \n to...
18
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, `"Hello World "`, `"HELLO "`, `"hello world hello world "` are all sentences. Words consist of **only** uppercase and lowercase English letters. Two sentences `sentence1` and `sentence2` are **similar** ...
The main point here is for the subarray to contain unique elements for each index. Only the first subarrays starting from that index have unique elements. This can be solved using the two pointers technique
PrefixSum Array + Sliding Window || Easy Solution
maximum-erasure-value
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nPrefixSum Array + Sliding Window \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can use the concept of prefix sum array to currect our current window sum in case of repeating element.\n\n# Complexity\n- Time...
2
You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements. Return _the **maximum score** you can get by erasing **exactly one** subarray._ An array `b` is called to be a subarray...
Indexes with higher frequencies should be bound with larger values
PrefixSum Array + Sliding Window || Easy Solution
maximum-erasure-value
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nPrefixSum Array + Sliding Window \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can use the concept of prefix sum array to currect our current window sum in case of repeating element.\n\n# Complexity\n- Time...
2
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, `"Hello World "`, `"HELLO "`, `"hello world hello world "` are all sentences. Words consist of **only** uppercase and lowercase English letters. Two sentences `sentence1` and `sentence2` are **similar** ...
The main point here is for the subarray to contain unique elements for each index. Only the first subarrays starting from that index have unique elements. This can be solved using the two pointers technique
Python Multiple Solution 1000 ms Fast solution
jump-game-vi
0
1
Using Deque:\n\n\t\t\n\tclass Solution:\n\t\tdef maxResult(self, nums: List[int], k: int) -> int:\n\t\t\tn = len(nums)\n\t\t\tdeq = deque([n-1])\n\t\t\tfor i in range(n-2, -1, -1):\n\t\t\t\tif deq[0] - i > k: deq.popleft()\n\t\t\t\tnums[i] += nums[deq[0]]\n\t\t\t\twhile len(deq) and nums[deq[-1]] <= nums[i]: deq.pop()\...
2
You are given a **0-indexed** integer array `nums` and an integer `k`. You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive*...
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
Python Multiple Solution 1000 ms Fast solution
jump-game-vi
0
1
Using Deque:\n\n\t\t\n\tclass Solution:\n\t\tdef maxResult(self, nums: List[int], k: int) -> int:\n\t\t\tn = len(nums)\n\t\t\tdeq = deque([n-1])\n\t\t\tfor i in range(n-2, -1, -1):\n\t\t\t\tif deq[0] - i > k: deq.popleft()\n\t\t\t\tnums[i] += nums[deq[0]]\n\t\t\t\twhile len(deq) and nums[deq[-1]] <= nums[i]: deq.pop()\...
2
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nu...
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value i...
Python (Simple Union Find)
checking-existence-of-edge-length-limited-paths
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
5
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes. Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for e...
BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string. O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*").
Python (Simple Union Find)
checking-existence-of-edge-length-limited-paths
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
5
There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve **all** of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `groups`, where `groups[i]` denotes that there is a group of `groups[i]` cust...
All the queries are given in advance. Is there a way you can reorder the queries to avoid repeated computations?
Python3 beats 87.42% 🚀🚀 quibler7
checking-existence-of-edge-length-limited-paths
0
1
# Code\n```\nclass Solution:\n def distanceLimitedPathsExist(self, n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]:\n \n parent = [i for i in range(n+1)]\n \n rank = [0 for i in range(n+1)]\n\n def find(parent, x):\n\n if parent[x] == x:\n ...
2
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes. Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for e...
BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string. O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*").
Python3 beats 87.42% 🚀🚀 quibler7
checking-existence-of-edge-length-limited-paths
0
1
# Code\n```\nclass Solution:\n def distanceLimitedPathsExist(self, n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]:\n \n parent = [i for i in range(n+1)]\n \n rank = [0 for i in range(n+1)]\n\n def find(parent, x):\n\n if parent[x] == x:\n ...
2
There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve **all** of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `groups`, where `groups[i]` denotes that there is a group of `groups[i]` cust...
All the queries are given in advance. Is there a way you can reorder the queries to avoid repeated computations?
Union Find python
checking-existence-of-edge-length-limited-paths
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes. Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for e...
BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string. O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*").
Union Find python
checking-existence-of-edge-length-limited-paths
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve **all** of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `groups`, where `groups[i]` denotes that there is a group of `groups[i]` cust...
All the queries are given in advance. Is there a way you can reorder the queries to avoid repeated computations?
Holy Moly !. Give it a try for this solution
checking-existence-of-edge-length-limited-paths
0
1
# Hint 1\nForget about multiple edges between two nodes. They are just to confuse. If we want the weight to be less than limitlimitlimit, just check with the minimum weight. We can always traverse a\u2194ba \\leftrightarrow ba\u2194b via minimum weighted edge if minWeight<limitmin.\n\n# Hint 2\nNormal traversal from so...
1
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes. Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for e...
BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string. O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*").
Holy Moly !. Give it a try for this solution
checking-existence-of-edge-length-limited-paths
0
1
# Hint 1\nForget about multiple edges between two nodes. They are just to confuse. If we want the weight to be less than limitlimitlimit, just check with the minimum weight. We can always traverse a\u2194ba \\leftrightarrow ba\u2194b via minimum weighted edge if minWeight<limitmin.\n\n# Hint 2\nNormal traversal from so...
1
There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve **all** of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `groups`, where `groups[i]` denotes that there is a group of `groups[i]` cust...
All the queries are given in advance. Is there a way you can reorder the queries to avoid repeated computations?
Python3 Solution
checking-existence-of-edge-length-limited-paths
0
1
\n```\nclass UnionFind:\n def __init__(self, N: int):\n self.parent = list(range(N))\n self.rank = [1] * N\n\n def find(self, p: int) -> int:\n if p != self.parent[p]:\n self.parent[p] = self.find(self.parent[p])\n return self.parent[p]\n\n def union(self, p: int, q: int)...
1
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes. Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for e...
BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string. O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*").
Python3 Solution
checking-existence-of-edge-length-limited-paths
0
1
\n```\nclass UnionFind:\n def __init__(self, N: int):\n self.parent = list(range(N))\n self.rank = [1] * N\n\n def find(self, p: int) -> int:\n if p != self.parent[p]:\n self.parent[p] = self.find(self.parent[p])\n return self.parent[p]\n\n def union(self, p: int, q: int)...
1
There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve **all** of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `groups`, where `groups[i]` denotes that there is a group of `groups[i]` cust...
All the queries are given in advance. Is there a way you can reorder the queries to avoid repeated computations?
Python disjoint-set union
checking-existence-of-edge-length-limited-paths
0
1
```python []\nclass DSU:\n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [0] * n\n\n def find(self, x):\n if self.parent[x] != x:\n self.parent[x] = self.find(self.parent[x])\n return self.parent[x]\n\n def union(self, x, y):\n x_root, y_root ...
1
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes. Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for e...
BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string. O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*").
Python disjoint-set union
checking-existence-of-edge-length-limited-paths
0
1
```python []\nclass DSU:\n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [0] * n\n\n def find(self, x):\n if self.parent[x] != x:\n self.parent[x] = self.find(self.parent[x])\n return self.parent[x]\n\n def union(self, x, y):\n x_root, y_root ...
1
There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve **all** of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `groups`, where `groups[i]` denotes that there is a group of `groups[i]` cust...
All the queries are given in advance. Is there a way you can reorder the queries to avoid repeated computations?
Image Explanation🏆- [Easiest & Complete Intuition] - C++/Java/Python
checking-existence-of-edge-length-limited-paths
1
1
# Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`Checking Existence of Edge Length Limited Paths` by `Aryan Mittal`\n![Google4.png](https://assets.leetcode.com/users/images/5e4850eb-7f31-417f-b101-c685af27e333_1682735486.275424.png)\n\n\n# Approach & Intution\n![image.png](https://assets.leetcode.com/user...
87
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes. Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for e...
BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string. O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*").
Image Explanation🏆- [Easiest & Complete Intuition] - C++/Java/Python
checking-existence-of-edge-length-limited-paths
1
1
# Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`Checking Existence of Edge Length Limited Paths` by `Aryan Mittal`\n![Google4.png](https://assets.leetcode.com/users/images/5e4850eb-7f31-417f-b101-c685af27e333_1682735486.275424.png)\n\n\n# Approach & Intution\n![image.png](https://assets.leetcode.com/user...
87
There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve **all** of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `groups`, where `groups[i]` denotes that there is a group of `groups[i]` cust...
All the queries are given in advance. Is there a way you can reorder the queries to avoid repeated computations?
✔💯 DAY 394 | Custom Union-Find | 100% 0ms | [PYTHON/JAVA/C++] | EXPLAINED | Approach 💫
checking-existence-of-edge-length-limited-paths
1
1
# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n\n![image.png](https://assets.leetcode.com/users/images/a2267944-10b8-41f2-b624-81a67ccea163_1680148646.205976.png)\n# Intuition & Approach\n<!-- Describe your approach to solving the problem. -->\n##### \u2022\tproblem is to determine if t...
31
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes. Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for e...
BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string. O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*").
✔💯 DAY 394 | Custom Union-Find | 100% 0ms | [PYTHON/JAVA/C++] | EXPLAINED | Approach 💫
checking-existence-of-edge-length-limited-paths
1
1
# Please Upvote as it really motivates me \uD83C\uDD99\uD83C\uDD99\uD83C\uDD99\n\n![image.png](https://assets.leetcode.com/users/images/a2267944-10b8-41f2-b624-81a67ccea163_1680148646.205976.png)\n# Intuition & Approach\n<!-- Describe your approach to solving the problem. -->\n##### \u2022\tproblem is to determine if t...
31
There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve **all** of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `groups`, where `groups[i]` denotes that there is a group of `groups[i]` cust...
All the queries are given in advance. Is there a way you can reorder the queries to avoid repeated computations?
[Python3] Union-Find
checking-existence-of-edge-length-limited-paths
0
1
**Algo**\nSort queries based on weight and sort edges based on weight as well. Scan through queries from lowest to highest weight and connect the edges whose weight strictly fall below this limit. Check if the queried nodes `p` and `q` are connected in Union-Find structure. If so, put `True` in the relevant position; o...
108
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes. Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for e...
BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string. O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*").
[Python3] Union-Find
checking-existence-of-edge-length-limited-paths
0
1
**Algo**\nSort queries based on weight and sort edges based on weight as well. Scan through queries from lowest to highest weight and connect the edges whose weight strictly fall below this limit. Check if the queried nodes `p` and `q` are connected in Union-Find structure. If so, put `True` in the relevant position; o...
108
There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve **all** of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `groups`, where `groups[i]` denotes that there is a group of `groups[i]` cust...
All the queries are given in advance. Is there a way you can reorder the queries to avoid repeated computations?
Simple Python Solution using Counter
number-of-students-unable-to-eat-lunch
0
1
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can distribute sandwich, if there is any student who wants that sandwich.\nSo, we create a counter of students.\nAnd, iterate sandwiches, one by one and check if there is any student left who wants that sandwich.\n\nIf there is a student who want...
2
The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers `0` and `1` respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed i...
Maintain the running sum and max value for repeated letters.
Simple Python Solution using Counter
number-of-students-unable-to-eat-lunch
0
1
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can distribute sandwich, if there is any student who wants that sandwich.\nSo, we create a counter of students.\nAnd, iterate sandwiches, one by one and check if there is any student left who wants that sandwich.\n\nIf there is a student who want...
2
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions: * `nums.length == n` * `nums[i]` is a **positive** integer where `0 <= i < n`. * `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`. * The sum of a...
Simulate the given in the statement Calculate those who will eat instead of those who will not.
Python Queue || easy || approach
number-of-students-unable-to-eat-lunch
0
1
```\nclass Solution:\n def countStudents(self, students: List[int], sandwiches: List[int]) -> int:\n count = 0\n while len(students) > count:\n if students[0] == sandwiches[0]:\n sandwiches.pop(0)\n count = 0\n else:\n students.append(s...
23
The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers `0` and `1` respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed i...
Maintain the running sum and max value for repeated letters.
Python Queue || easy || approach
number-of-students-unable-to-eat-lunch
0
1
```\nclass Solution:\n def countStudents(self, students: List[int], sandwiches: List[int]) -> int:\n count = 0\n while len(students) > count:\n if students[0] == sandwiches[0]:\n sandwiches.pop(0)\n count = 0\n else:\n students.append(s...
23
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions: * `nums.length == n` * `nums[i]` is a **positive** integer where `0 <= i < n`. * `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`. * The sum of a...
Simulate the given in the statement Calculate those who will eat instead of those who will not.
Easy Approach
number-of-students-unable-to-eat-lunch
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
5
The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers `0` and `1` respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed i...
Maintain the running sum and max value for repeated letters.
Easy Approach
number-of-students-unable-to-eat-lunch
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
5
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions: * `nums.length == n` * `nums[i]` is a **positive** integer where `0 <= i < n`. * `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`. * The sum of a...
Simulate the given in the statement Calculate those who will eat instead of those who will not.
Simple solution by using Deque DS
number-of-students-unable-to-eat-lunch
0
1
# Intuition\nThe task description clearly describes the path to resolve the problem.\n\n```\n# each student can take a sandwich \n# according to it\'s index (that\'s 1 OR 0)\n# from sandwiches stack\n\n# the simplest example and pseudocode\nsandwiches = [1, 0, 1]\nstudents = [0, 1, 1]\n\n# while sandwiches\n# i = 0 => ...
3
The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers `0` and `1` respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed i...
Maintain the running sum and max value for repeated letters.
Simple solution by using Deque DS
number-of-students-unable-to-eat-lunch
0
1
# Intuition\nThe task description clearly describes the path to resolve the problem.\n\n```\n# each student can take a sandwich \n# according to it\'s index (that\'s 1 OR 0)\n# from sandwiches stack\n\n# the simplest example and pseudocode\nsandwiches = [1, 0, 1]\nstudents = [0, 1, 1]\n\n# while sandwiches\n# i = 0 => ...
3
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions: * `nums.length == n` * `nums[i]` is a **positive** integer where `0 <= i < n`. * `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`. * The sum of a...
Simulate the given in the statement Calculate those who will eat instead of those who will not.
100% speed Python [No imports][Simple to understand / commented!]
number-of-students-unable-to-eat-lunch
0
1
Code: \n```\ndef countStu(stu,sand):\n while sand:\n if sand[0] in stu:\n stu.remove(sand[0])\n sand.pop(0)\n else:break\n return len(sand)\n```\n\nCommented Code:\n```\ndef countStu(stu,sand):\n\t# while there are still elements in sandwich list\n while sand:\n\t\t# check i...
30
The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers `0` and `1` respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed i...
Maintain the running sum and max value for repeated letters.
100% speed Python [No imports][Simple to understand / commented!]
number-of-students-unable-to-eat-lunch
0
1
Code: \n```\ndef countStu(stu,sand):\n while sand:\n if sand[0] in stu:\n stu.remove(sand[0])\n sand.pop(0)\n else:break\n return len(sand)\n```\n\nCommented Code:\n```\ndef countStu(stu,sand):\n\t# while there are still elements in sandwich list\n while sand:\n\t\t# check i...
30
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions: * `nums.length == n` * `nums[i]` is a **positive** integer where `0 <= i < n`. * `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`. * The sum of a...
Simulate the given in the statement Calculate those who will eat instead of those who will not.
Python using queue push pop
number-of-students-unable-to-eat-lunch
0
1
```\nclass Solution:\n def countStudents(self, students: List[int], sandwiches: List[int]) -> int:\n count = len(students)\n while(sandwiches and students and sandwiches[0] in students):\n if(sandwiches[0]!=students[0]):\n students.append(students[0])\n students...
3
The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers `0` and `1` respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed i...
Maintain the running sum and max value for repeated letters.
Python using queue push pop
number-of-students-unable-to-eat-lunch
0
1
```\nclass Solution:\n def countStudents(self, students: List[int], sandwiches: List[int]) -> int:\n count = len(students)\n while(sandwiches and students and sandwiches[0] in students):\n if(sandwiches[0]!=students[0]):\n students.append(students[0])\n students...
3
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions: * `nums.length == n` * `nums[i]` is a **positive** integer where `0 <= i < n`. * `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`. * The sum of a...
Simulate the given in the statement Calculate those who will eat instead of those who will not.
[Python3] 32ms Brute Force Solution
number-of-students-unable-to-eat-lunch
0
1
```\nclass Solution:\n def countStudents(self, students: List[int], sandwiches: List[int]) -> int:\n curr = 0\n \n while students:\n if(students[0] == sandwiches[0]):\n curr = 0\n students.pop(0)\n sandwiches.pop(0)\n else:\n ...
11
The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers `0` and `1` respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed i...
Maintain the running sum and max value for repeated letters.
[Python3] 32ms Brute Force Solution
number-of-students-unable-to-eat-lunch
0
1
```\nclass Solution:\n def countStudents(self, students: List[int], sandwiches: List[int]) -> int:\n curr = 0\n \n while students:\n if(students[0] == sandwiches[0]):\n curr = 0\n students.pop(0)\n sandwiches.pop(0)\n else:\n ...
11
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions: * `nums.length == n` * `nums[i]` is a **positive** integer where `0 <= i < n`. * `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`. * The sum of a...
Simulate the given in the statement Calculate those who will eat instead of those who will not.
Python Elegant & Short | One Pass
average-waiting-time
0
1
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def averageWaitingTime(self, customers: List[List[int]]) -> float:\n finish_time = -maxsize\n total_wait_time = 0\n\n for time, duration in customers:\n if time < finish_time:\n ...
1
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:` * `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order. * `timei` is the time needed to prepare the order of the `ith` customer. When a ...
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use ...
Python Elegant & Short | One Pass
average-waiting-time
0
1
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def averageWaitingTime(self, customers: List[List[int]]) -> float:\n finish_time = -maxsize\n total_wait_time = 0\n\n for time, duration in customers:\n if time < finish_time:\n ...
1
Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_. A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`. **Example 1:** **Input:** nums = \[1,4,2,7\], low = 2, high = 6 **Output:** 6 **Explan...
Iterate on the customers, maintaining the time the chef will finish the previous orders. If that time is before the current arrival time, the chef starts immediately. Else, the current customer waits till the chef finishes, and then the chef starts. Update the running time by the time when the chef starts preparing + p...
Beginner Friendly || Easy Understandable solution || Python 3
average-waiting-time
0
1
\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def averageWaitingTime(self, arr: List[List[int]]) -> float:\n a=[[arr[0][0],arr[0][0]+arr[0][1]]]\n for i in range(1,len(arr)):\n if arr[i][0]>a[-1][1]:\n a.append([arr[i][...
1
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:` * `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order. * `timei` is the time needed to prepare the order of the `ith` customer. When a ...
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use ...
Beginner Friendly || Easy Understandable solution || Python 3
average-waiting-time
0
1
\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def averageWaitingTime(self, arr: List[List[int]]) -> float:\n a=[[arr[0][0],arr[0][0]+arr[0][1]]]\n for i in range(1,len(arr)):\n if arr[i][0]>a[-1][1]:\n a.append([arr[i][...
1
Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_. A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`. **Example 1:** **Input:** nums = \[1,4,2,7\], low = 2, high = 6 **Output:** 6 **Explan...
Iterate on the customers, maintaining the time the chef will finish the previous orders. If that time is before the current arrival time, the chef starts immediately. Else, the current customer waits till the chef finishes, and then the chef starts. Update the running time by the time when the chef starts preparing + p...
Easy Approach
average-waiting-time
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
3
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:` * `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order. * `timei` is the time needed to prepare the order of the `ith` customer. When a ...
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use ...
Easy Approach
average-waiting-time
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
3
Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_. A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`. **Example 1:** **Input:** nums = \[1,4,2,7\], low = 2, high = 6 **Output:** 6 **Explan...
Iterate on the customers, maintaining the time the chef will finish the previous orders. If that time is before the current arrival time, the chef starts immediately. Else, the current customer waits till the chef finishes, and then the chef starts. Update the running time by the time when the chef starts preparing + p...
✅⬆️🔥 BEATS 100 % | 0ms | 3 lines | easy | proof
average-waiting-time
1
1
# UPVOTE please\n![image.png](https://assets.leetcode.com/users/images/6fce2597-704a-4079-916e-924110b7b0b7_1671379155.9872167.png)\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# C...
2
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:` * `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order. * `timei` is the time needed to prepare the order of the `ith` customer. When a ...
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use ...
✅⬆️🔥 BEATS 100 % | 0ms | 3 lines | easy | proof
average-waiting-time
1
1
# UPVOTE please\n![image.png](https://assets.leetcode.com/users/images/6fce2597-704a-4079-916e-924110b7b0b7_1671379155.9872167.png)\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# C...
2
Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_. A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`. **Example 1:** **Input:** nums = \[1,4,2,7\], low = 2, high = 6 **Output:** 6 **Explan...
Iterate on the customers, maintaining the time the chef will finish the previous orders. If that time is before the current arrival time, the chef starts immediately. Else, the current customer waits till the chef finishes, and then the chef starts. Update the running time by the time when the chef starts preparing + p...
[Python3] Simple And Fast Solution
average-waiting-time
0
1
```\nclass Solution:\n def averageWaitingTime(self, customers: List[List[int]]) -> float:\n arr = []\n \n time = 0\n \n for i , j in customers:\n if(i > time):\n time = i + j\n else:\n time += j\n arr.append(time - i)\n...
7
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:` * `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order. * `timei` is the time needed to prepare the order of the `ith` customer. When a ...
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use ...
[Python3] Simple And Fast Solution
average-waiting-time
0
1
```\nclass Solution:\n def averageWaitingTime(self, customers: List[List[int]]) -> float:\n arr = []\n \n time = 0\n \n for i , j in customers:\n if(i > time):\n time = i + j\n else:\n time += j\n arr.append(time - i)\n...
7
Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_. A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`. **Example 1:** **Input:** nums = \[1,4,2,7\], low = 2, high = 6 **Output:** 6 **Explan...
Iterate on the customers, maintaining the time the chef will finish the previous orders. If that time is before the current arrival time, the chef starts immediately. Else, the current customer waits till the chef finishes, and then the chef starts. Update the running time by the time when the chef starts preparing + p...
Easy Python solution (ACCEPTED)
average-waiting-time
0
1
**Explanation**\nFirstly, we get the initial customer arrival time as actual time, then go through all customers one by one with special logic. We add waiting to time to actual time. If the next arrival time is bigger than the current actual time, it means that customer ordered it when chef is free.\n**Complexity**\n\n...
6
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:` * `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order. * `timei` is the time needed to prepare the order of the `ith` customer. When a ...
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use ...
Easy Python solution (ACCEPTED)
average-waiting-time
0
1
**Explanation**\nFirstly, we get the initial customer arrival time as actual time, then go through all customers one by one with special logic. We add waiting to time to actual time. If the next arrival time is bigger than the current actual time, it means that customer ordered it when chef is free.\n**Complexity**\n\n...
6
Given a **(0-indexed)** integer array `nums` and two integers `low` and `high`, return _the number of **nice pairs**_. A **nice pair** is a pair `(i, j)` where `0 <= i < j < nums.length` and `low <= (nums[i] XOR nums[j]) <= high`. **Example 1:** **Input:** nums = \[1,4,2,7\], low = 2, high = 6 **Output:** 6 **Explan...
Iterate on the customers, maintaining the time the chef will finish the previous orders. If that time is before the current arrival time, the chef starts immediately. Else, the current customer waits till the chef finishes, and then the chef starts. Update the running time by the time when the chef starts preparing + p...
brute force
average-waiting-time
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:` * `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order. * `timei` is the time needed to prepare the order of the `ith` customer. When a ...
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use ...