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
Python 1L / Rust 2-3 L / Go a lot.
sort-integers-by-the-number-of-1-bits
0
1
# Intuition\nAll you need is to count the number of ones, create tules of `(cnt, v)` and then do sorting. Many languages allow to do this in one line\n\n# Complexity\n- Time complexity: $O(n \\log n)$\n- Space complexity: $O(n)$\n\n# Code\n```Rust []\nimpl Solution {\n pub fn sort_by_bits(arr: Vec<i32>) -> Vec<i32> {\...
1
Given two arrays `nums1` and `nums2`. Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of...
Simulate the problem. Count the number of 1's in the binary representation of each integer. Sort by the number of 1's ascending and by the value in case of tie.
✅ Beats 94.41 %🔥 || within 4 Lines of Code || Hash Table 🚀 ||
sort-integers-by-the-number-of-1-bits
1
1
![Screenshot 2023-10-30 at 8.19.03\u202FAM.png](https://assets.leetcode.com/users/images/0b405fc3-359f-4627-9bba-68d8cab06268_1698634368.229628.png)\n\n# Intuition:\n**Here we use a dictionary to store the number of 1\'s in the binary representation of each number in the array. Then we sort the keys of the dictionary a...
12
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr ...
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
✅ Beats 94.41 %🔥 || within 4 Lines of Code || Hash Table 🚀 ||
sort-integers-by-the-number-of-1-bits
1
1
![Screenshot 2023-10-30 at 8.19.03\u202FAM.png](https://assets.leetcode.com/users/images/0b405fc3-359f-4627-9bba-68d8cab06268_1698634368.229628.png)\n\n# Intuition:\n**Here we use a dictionary to store the number of 1\'s in the binary representation of each number in the array. Then we sort the keys of the dictionary a...
12
Given two arrays `nums1` and `nums2`. Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of...
Simulate the problem. Count the number of 1's in the binary representation of each integer. Sort by the number of 1's ascending and by the value in case of tie.
Beats 100% in Time Complexity
apply-discount-every-n-orders
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. -->\nMaintain hashmap for product and price mapping. Then it would be pretty straight forward solution\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity he...
0
There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays `products` and `prices`, where the `ith` product has an ID of `products[i]` and a price of `prices[i]`. When a customer is paying, their bill is represented as two parallel i...
null
Simple and clear python3 solutions | 617 ms - faster than 96.1% solutions
apply-discount-every-n-orders
0
1
# Complexity\n- Time complexity: $$O(m)$$ for `__init__` and `getBill`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(m)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nwhere `m = products.length`\n\n# Code\n``` python3 []\nclass Cashier:\n def __init__(self, n: int, dis...
0
There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays `products` and `prices`, where the `ith` product has an ID of `products[i]` and a price of `prices[i]`. When a customer is paying, their bill is represented as two parallel i...
null
✅ Python Simple Class Structure ✅
apply-discount-every-n-orders
0
1
# Code\n```\nclass Cashier:\n\n def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):\n self.n = n\n self.current = 0\n self.discount = discount\n self.d = {products[i]:prices[i] for i in range(len(products))}\n\n def getBill(self, product: List[int], amoun...
0
There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays `products` and `prices`, where the `ith` product has an ID of `products[i]` and a price of `prices[i]`. When a customer is paying, their bill is represented as two parallel i...
null
Python Easy solution using dict
apply-discount-every-n-orders
0
1
```\nclass Cashier:\n\n def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):\n self.dis = discount / 100\n self.currentCustomer = 0\n self.n = n\n self.products = {i: j for i, j in zip(products, prices)}\n\n def getBill(self, product: List[int], amount: L...
0
There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays `products` and `prices`, where the `ith` product has an ID of `products[i]` and a price of `prices[i]`. When a customer is paying, their bill is represented as two parallel i...
null
[Python3] Good enough
apply-discount-every-n-orders
0
1
``` Python3 []\nclass Cashier:\n\n def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):\n self.lucky = n\n self.discount = discount\n self.costs = {}\n self.customers = 0\n\n for i in range(len(products)):\n self.costs[products[i]] = prices[...
0
There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays `products` and `prices`, where the `ith` product has an ID of `products[i]` and a price of `prices[i]`. When a customer is paying, their bill is represented as two parallel i...
null
Python clear solution.
apply-discount-every-n-orders
0
1
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThat\'s pretty much self-explanatory. Store the prices in dictionary for speed.\nValue "c" counts if it\'s time to give a discount.\n\n\n# Code\n```\nclass Cashier:\n\n def __init__(self, n: int, discount: int, products: List[int], prices: List[i...
0
There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays `products` and `prices`, where the `ith` product has an ID of `products[i]` and a price of `prices[i]`. When a customer is paying, their bill is represented as two parallel i...
null
Sliding Window - O(n)
number-of-substrings-containing-all-three-characters
0
1
# Approach\n1) Move the window from 0->n, with incrementing the character count in map/dict\n2) When count of each chars in dict is set [could be =1 or >1], we have a valid substring\n3) From valid substring\'s end [window end /right pointer], count how many other substrings are possible and add it to result\n\nDry Run...
4
Given a string `s` consisting only of characters _a_, _b_ and _c_. Return the number of substrings containing **at least** one occurrence of all these characters _a_, _b_ and _c_. **Example 1:** **Input:** s = "abcabc " **Output:** 10 **Explanation:** The substrings containing at least one occurrence of the charact...
Loop over 1 ≤ x,y ≤ 1000 and check if f(x,y) == z.
Sliding Window - O(n)
number-of-substrings-containing-all-three-characters
0
1
# Approach\n1) Move the window from 0->n, with incrementing the character count in map/dict\n2) When count of each chars in dict is set [could be =1 or >1], we have a valid substring\n3) From valid substring\'s end [window end /right pointer], count how many other substrings are possible and add it to result\n\nDry Run...
4
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps. Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_. **Example 1:** **Input:** target = \[1,...
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
Python 3 | Two Pointers | Explanation
number-of-substrings-containing-all-three-characters
0
1
### Explanation\n- Two pointer to same direction, fast pointer check new character, slow pointer shorten substr\n- Use a little math (`n-j`) to count possible valid substrings\n- Check comments for more detail\n### Implementation\n```\nclass Solution:\n def numberOfSubstrings(self, s: str) -> int:\n a = b = c...
35
Given a string `s` consisting only of characters _a_, _b_ and _c_. Return the number of substrings containing **at least** one occurrence of all these characters _a_, _b_ and _c_. **Example 1:** **Input:** s = "abcabc " **Output:** 10 **Explanation:** The substrings containing at least one occurrence of the charact...
Loop over 1 ≤ x,y ≤ 1000 and check if f(x,y) == z.
Python 3 | Two Pointers | Explanation
number-of-substrings-containing-all-three-characters
0
1
### Explanation\n- Two pointer to same direction, fast pointer check new character, slow pointer shorten substr\n- Use a little math (`n-j`) to count possible valid substrings\n- Check comments for more detail\n### Implementation\n```\nclass Solution:\n def numberOfSubstrings(self, s: str) -> int:\n a = b = c...
35
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps. Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_. **Example 1:** **Input:** target = \[1,...
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
Simple Solution || Beginner Friendly || Easy to Understand || O(n) 🔥
count-all-valid-pickup-and-delivery-options
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou have `n` items to be delivered, and you need to find the number of different valid orders in which you can deliver these items.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nDynamic Programming Approach:\n- Ini...
10
Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation:** Unique order (P1, ...
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
Simple Solution || Beginner Friendly || Easy to Understand || O(n) 🔥
count-all-valid-pickup-and-delivery-options
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou have `n` items to be delivered, and you need to find the number of different valid orders in which you can deliver these items.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nDynamic Programming Approach:\n- Ini...
10
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f...
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
C++/Python Math recursion->1 loop->1 line
count-all-valid-pickup-and-delivery-options
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is a permutation problem.\n$$\nF(n)=\\frac{(2n)!}{2^n}\n$$\nUse the recurrence\n$$\nF(n+1)=F(n)\\times(n+1)\\times (2n+1)\n$$\n# Approach\n<!-- Describe your approach to solving the problem. -->\n[Please turn on English subtitles if ...
10
Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation:** Unique order (P1, ...
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
C++/Python Math recursion->1 loop->1 line
count-all-valid-pickup-and-delivery-options
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is a permutation problem.\n$$\nF(n)=\\frac{(2n)!}{2^n}\n$$\nUse the recurrence\n$$\nF(n+1)=F(n)\\times(n+1)\\times (2n+1)\n$$\n# Approach\n<!-- Describe your approach to solving the problem. -->\n[Please turn on English subtitles if ...
10
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f...
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
✔96.89% Beats C++😍||Hard-->Easy✨|| Easy to understand 📈🧠|| With commented code 😇|| #Beginner😉😎
count-all-valid-pickup-and-delivery-options
1
1
# Problem Understanding:\n\n- The problem is asking us to count the number of valid orders in which \'n\' items can be arranged. \n- Each item takes up two places, and we want to find the total number of valid sequences for these items.\n\n# Strategies to Tackle the Problem:\n\n**Initialize Variables:**\n\n- Initialize...
5
Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation:** Unique order (P1, ...
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
✔96.89% Beats C++😍||Hard-->Easy✨|| Easy to understand 📈🧠|| With commented code 😇|| #Beginner😉😎
count-all-valid-pickup-and-delivery-options
1
1
# Problem Understanding:\n\n- The problem is asking us to count the number of valid orders in which \'n\' items can be arranged. \n- Each item takes up two places, and we want to find the total number of valid sequences for these items.\n\n# Strategies to Tackle the Problem:\n\n**Initialize Variables:**\n\n- Initialize...
5
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f...
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
Python | Easy to Understand | Fast | Optimal Solution
count-all-valid-pickup-and-delivery-options
0
1
# Python | Easy to Understand | Fast | Optimal Solution\n```\nfrom functools import reduce\nfrom operator import mul\nclass Solution:\n def countOrders(self, n: int) -> int:\n return reduce(mul, (*range(1,n+1), *range(1,2*n,2)), 1) % (10**9+7)\n```
13
Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation:** Unique order (P1, ...
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
Python | Easy to Understand | Fast | Optimal Solution
count-all-valid-pickup-and-delivery-options
0
1
# Python | Easy to Understand | Fast | Optimal Solution\n```\nfrom functools import reduce\nfrom operator import mul\nclass Solution:\n def countOrders(self, n: int) -> int:\n return reduce(mul, (*range(1,n+1), *range(1,2*n,2)), 1) % (10**9+7)\n```
13
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f...
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
Python Simple Solution with time complexity O(n)
count-all-valid-pickup-and-delivery-options
0
1
# Intuition\n\nWe have n orders means total 2n options,out of 2n places1st place is always placeorder and further places could be place order or delivered, last place will always be delivered.\n\n- The intuition behind this code is to calculate the total number of valid orderings of n different products in 2n available...
3
Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation:** Unique order (P1, ...
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
Python Simple Solution with time complexity O(n)
count-all-valid-pickup-and-delivery-options
0
1
# Intuition\n\nWe have n orders means total 2n options,out of 2n places1st place is always placeorder and further places could be place order or delivered, last place will always be delivered.\n\n- The intuition behind this code is to calculate the total number of valid orderings of n different products in 2n available...
3
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f...
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
✅ 99.57% DP & Math & Recursion
count-all-valid-pickup-and-delivery-options
1
1
# Comprehensive Guide to Solving "Count All Valid Pickup and Delivery Options": Dynamic Programming, Recursion, and Math Approaches\n\n## Introduction & Problem Statement\n\nGreetings, aspiring problem solvers! Today we\'ll unravel an intriguing combinatorial problem that revolves around orders, pickups, and deliveries...
124
Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation:** Unique order (P1, ...
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
✅ 99.57% DP & Math & Recursion
count-all-valid-pickup-and-delivery-options
1
1
# Comprehensive Guide to Solving "Count All Valid Pickup and Delivery Options": Dynamic Programming, Recursion, and Math Approaches\n\n## Introduction & Problem Statement\n\nGreetings, aspiring problem solvers! Today we\'ll unravel an intriguing combinatorial problem that revolves around orders, pickups, and deliveries...
124
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f...
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
Python shortest 1-liner. Functional programming.
count-all-valid-pickup-and-delivery-options
0
1
# Approach\n$$ways(n) = \\left(\\sum_{x=1}^{2(n-1)+1} x\\right) \\cdot ways(n-1) = 2n! \\div 2^n$$\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```python\nclass Solution:\n def countOrders(self, n: int) -> int:\n return (factorial(2 * n) // pow(2, n)) % 1_000_000_007...
2
Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation:** Unique order (P1, ...
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
Python shortest 1-liner. Functional programming.
count-all-valid-pickup-and-delivery-options
0
1
# Approach\n$$ways(n) = \\left(\\sum_{x=1}^{2(n-1)+1} x\\right) \\cdot ways(n-1) = 2n! \\div 2^n$$\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```python\nclass Solution:\n def countOrders(self, n: int) -> int:\n return (factorial(2 * n) // pow(2, n)) % 1_000_000_007...
2
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f...
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
Python3 Solution
count-all-valid-pickup-and-delivery-options
0
1
\n```\nclass Solution:\n def countOrders(self, n: int) -> int:\n mod=10**9+7\n ans=math.factorial(n*2)>>n\n return ans%mod\n```
2
Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation:** Unique order (P1, ...
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
Python3 Solution
count-all-valid-pickup-and-delivery-options
0
1
\n```\nclass Solution:\n def countOrders(self, n: int) -> int:\n mod=10**9+7\n ans=math.factorial(n*2)>>n\n return ans%mod\n```
2
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f...
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
【Video】Easy way to think about this question! - Python, JavaScript, Java and C++
count-all-valid-pickup-and-delivery-options
1
1
# Intuition\nBreak down the question into a small case, so that you can understand it easily.\n\n---\n\n# Solution Video\n\n### \u2B50\uFE0F Please subscribe to my channel from here. I have 258 videos as of September 10th, 2023.\n\nIn the video, the steps of approach below are visualized using diagrams and drawings. I\...
30
Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation:** Unique order (P1, ...
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
【Video】Easy way to think about this question! - Python, JavaScript, Java and C++
count-all-valid-pickup-and-delivery-options
1
1
# Intuition\nBreak down the question into a small case, so that you can understand it easily.\n\n---\n\n# Solution Video\n\n### \u2B50\uFE0F Please subscribe to my channel from here. I have 258 videos as of September 10th, 2023.\n\nIn the video, the steps of approach below are visualized using diagrams and drawings. I\...
30
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f...
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
🚀 Beats 100% || C++ || Java || Python || DP Recursive & Iterative || Commented Code🚀
count-all-valid-pickup-and-delivery-options
1
1
# Problem Description\n\nYou are given `n` orders, each comprising both **pickup** and **delivery** services. The task is to **count** all the valid sequences of these orders, ensuring that the delivery for each order always occurs after its corresponding pickup. To manage large results, return the count modulo `10^9 +...
62
Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation:** Unique order (P1, ...
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
🚀 Beats 100% || C++ || Java || Python || DP Recursive & Iterative || Commented Code🚀
count-all-valid-pickup-and-delivery-options
1
1
# Problem Description\n\nYou are given `n` orders, each comprising both **pickup** and **delivery** services. The task is to **count** all the valid sequences of these orders, ensuring that the delivery for each order always occurs after its corresponding pickup. To manage large results, return the count modulo `10^9 +...
62
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f...
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
A solution you shouldn't read.
count-all-valid-pickup-and-delivery-options
0
1
# Intuition\nNO intuition at all ppl\n# Approach\nGuessing.\n# Complexity\n- Time complexity:\nO(1) this is as fast as it can get. Assuming python can do the factorial and the power in O(1) which is not the case.\n- Space complexity:\nO(1)\n# Code\n```\nclass Solution:\n def countOrders(self, n: int) -> int:\n\n ...
1
Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation:** Unique order (P1, ...
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
A solution you shouldn't read.
count-all-valid-pickup-and-delivery-options
0
1
# Intuition\nNO intuition at all ppl\n# Approach\nGuessing.\n# Complexity\n- Time complexity:\nO(1) this is as fast as it can get. Assuming python can do the factorial and the power in O(1) which is not the case.\n- Space complexity:\nO(1)\n# Code\n```\nclass Solution:\n def countOrders(self, n: int) -> int:\n\n ...
1
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f...
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
simple One liner python easy to understand
count-all-valid-pickup-and-delivery-options
0
1
# Code\n```python\nclass Solution:\n def countOrders(self, n: int) -> int:\n return (factorial(2*n) // (2**n)) % (10**9 + 7)\n \n \n```
1
Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation:** Unique order (P1, ...
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
simple One liner python easy to understand
count-all-valid-pickup-and-delivery-options
0
1
# Code\n```python\nclass Solution:\n def countOrders(self, n: int) -> int:\n return (factorial(2*n) // (2**n)) % (10**9 + 7)\n \n \n```
1
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f...
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
Easy solution || Python
count-all-valid-pickup-and-delivery-options
0
1
# Approach\nThe formula seems to be based on the observation that for each additional order, you have two choices for the pickup and delivery locations: you can either insert the pickup and its corresponding delivery at the beginning or insert them at the end of the existing sequence. The `(2*i-1)*i` term represents th...
1
Given `n` orders, each order consist in pickup and delivery services. Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). Since the answer may be too large, return it modulo 10^9 + 7. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation:** Unique order (P1, ...
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
Easy solution || Python
count-all-valid-pickup-and-delivery-options
0
1
# Approach\nThe formula seems to be based on the observation that for each additional order, you have two choices for the pickup and delivery locations: you can either insert the pickup and its corresponding delivery at the beginning or insert them at the end of the existing sequence. The `(2*i-1)*i` term represents th...
1
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f...
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
Python solution ( using datetime )
number-of-days-between-two-dates
0
1
```\nfrom datetime import datetime\n\nclass Solution:\n def daysBetweenDates(self, date1: str, date2: str) -> int:\n a: list(int) = [int(number) for number in date1.split("-")]\n b: list(int) = [int(number) for number in date2.split("-")]\n\n a: float = datetime(*a).timestamp()\n b: float...
1
Write a program to count the number of days between two dates. The two dates are given as strings, their format is `YYYY-MM-DD` as shown in the examples. **Example 1:** **Input:** date1 = "2019-06-29", date2 = "2019-06-30" **Output:** 1 **Example 2:** **Input:** date1 = "2020-01-15", date2 = "2019-12-31" **Output:...
You can try all combinations and keep mask of characters you have. You can use DP.
Python easy.. but I got 茴字有3种写法
number-of-days-between-two-dates
0
1
# Intuition\n\u8334\u5B57\u67093\u79CD\u5199\u6CD5\n\n# Code\n```\n def daysBetweenDates(self, date1: str, date2: str) -> int:\n \n y,m,d = date1.split("-")\n date_format = "%Y-%m-%d"\n\n a = datetime.datetime.strptime(date1, date_format)\n b = datetime.datetime.strptime(date2, dat...
1
Write a program to count the number of days between two dates. The two dates are given as strings, their format is `YYYY-MM-DD` as shown in the examples. **Example 1:** **Input:** date1 = "2019-06-29", date2 = "2019-06-30" **Output:** 1 **Example 2:** **Input:** date1 = "2020-01-15", date2 = "2019-12-31" **Output:...
You can try all combinations and keep mask of characters you have. You can use DP.
Simple & Easy Solution by Python 3
number-of-days-between-two-dates
0
1
```\nclass Solution:\n def daysBetweenDates(self, date1: str, date2: str) -> int:\n def is_leap_year(year: int) -> bool:\n return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)\n\n def get_days(date: str) -> int:\n y, m, d = map(int, date.split(\'-\'))\n\n days ...
13
Write a program to count the number of days between two dates. The two dates are given as strings, their format is `YYYY-MM-DD` as shown in the examples. **Example 1:** **Input:** date1 = "2019-06-29", date2 = "2019-06-30" **Output:** 1 **Example 2:** **Input:** date1 = "2020-01-15", date2 = "2019-12-31" **Output:...
You can try all combinations and keep mask of characters you have. You can use DP.
Python 3 - One Liner Using DATETIME
number-of-days-between-two-dates
0
1
Approach:\n1. The input is of type <```string```>. To use the datetime module, these strings will first be converted into type <```date```> using ```datetime.strptime(date_string, format)```.\n2. After conversion, the dates are subtracted, i.e. ```(date2 - date1).days()```\n\nNote:\n```abs()``` must be used when calcul...
16
Write a program to count the number of days between two dates. The two dates are given as strings, their format is `YYYY-MM-DD` as shown in the examples. **Example 1:** **Input:** date1 = "2019-06-29", date2 = "2019-06-30" **Output:** 1 **Example 2:** **Input:** date1 = "2020-01-15", date2 = "2019-12-31" **Output:...
You can try all combinations and keep mask of characters you have. You can use DP.
Python3 Datetime approach
number-of-days-between-two-dates
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. -->\nDatetime\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here...
2
Write a program to count the number of days between two dates. The two dates are given as strings, their format is `YYYY-MM-DD` as shown in the examples. **Example 1:** **Input:** date1 = "2019-06-29", date2 = "2019-06-30" **Output:** 1 **Example 2:** **Input:** date1 = "2020-01-15", date2 = "2019-12-31" **Output:...
You can try all combinations and keep mask of characters you have. You can use DP.
Python3 Solution from Scratch - NOT USING DATETIME
number-of-days-between-two-dates
0
1
```\nclass Solution:\n def daysBetweenDates(self, date1: str, date2: str) -> int:\n \n def f_date(date): # calculates days passed since \'1900-01-01\'\n year0 = \'1900\'\n year1, month1, day1 = date.split(\'-\')\n \n days = 0\n for y in...
4
Write a program to count the number of days between two dates. The two dates are given as strings, their format is `YYYY-MM-DD` as shown in the examples. **Example 1:** **Input:** date1 = "2019-06-29", date2 = "2019-06-30" **Output:** 1 **Example 2:** **Input:** date1 = "2020-01-15", date2 = "2019-12-31" **Output:...
You can try all combinations and keep mask of characters you have. You can use DP.
mySolution
number-of-days-between-two-dates
0
1
# Code\n```\nfrom datetime import datetime\nclass Solution:\n def daysBetweenDates(self, date1: str, date2: str) -> int:\n date_format = "%Y-%m-%d"\n return abs((datetime.strptime(date1, date_format)-datetime.strptime(date2,date_format)).days)\n```
0
Write a program to count the number of days between two dates. The two dates are given as strings, their format is `YYYY-MM-DD` as shown in the examples. **Example 1:** **Input:** date1 = "2019-06-29", date2 = "2019-06-30" **Output:** 1 **Example 2:** **Input:** date1 = "2020-01-15", date2 = "2019-12-31" **Output:...
You can try all combinations and keep mask of characters you have. You can use DP.
Number of days between two dates
number-of-days-between-two-dates
0
1
\n# Code\n```\nclass Solution:\n def daysBetweenDates(self, date1: str, date2: str) -> int:\n def isl(year):\n return (year% 4==0) and (year%100!=0) or (year%400==0)\n\n k = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]\n\n y1, m1, d1 = map(int, date1.split("-"))\n ...
0
Write a program to count the number of days between two dates. The two dates are given as strings, their format is `YYYY-MM-DD` as shown in the examples. **Example 1:** **Input:** date1 = "2019-06-29", date2 = "2019-06-30" **Output:** 1 **Example 2:** **Input:** date1 = "2020-01-15", date2 = "2019-12-31" **Output:...
You can try all combinations and keep mask of characters you have. You can use DP.
✅ 82.42% Easy BFS
validate-binary-tree-nodes
1
1
# Intuition\nInitially, we can observe that in a valid binary tree, there should be exactly one node with an in-degree of 0 (the root), and all other nodes should have an in-degree of 1. Furthermore, all nodes should be reachable from the root node. These observations form the basis of our approach to solving this prob...
50
You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree. If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child. ...
Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m).
✅ 82.42% Easy BFS
validate-binary-tree-nodes
1
1
# Intuition\nInitially, we can observe that in a valid binary tree, there should be exactly one node with an in-degree of 0 (the root), and all other nodes should have an in-degree of 1. Furthermore, all nodes should be reachable from the root node. These observations form the basis of our approach to solving this prob...
50
**Tic-tac-toe** is played by two players `A` and `B` on a `3 x 3` grid. The rules of Tic-Tac-Toe are: * Players take turns placing characters into empty squares `' '`. * The first player `A` always places `'X'` characters, while the second player `B` always places `'O'` characters. * `'X'` and `'O'` characters a...
Find the parent of each node. A valid tree must have nodes with only one parent and exactly one node with no parent.
🚀 93.31% || BFS & DFS || Explained Intuition🚀
validate-binary-tree-nodes
1
1
# Porblem Description\n\nGiven `n` binary tree nodes numbered from `0` to `n - 1`, represented by arrays `leftChild` and `rightChild` where each element corresponds to the `left` and `right` child of a node respectively, **determine** if the provided nodes **form** exactly one **valid** binary tree. \nA node with **no ...
93
You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree. If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child. ...
Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m).
🚀 93.31% || BFS & DFS || Explained Intuition🚀
validate-binary-tree-nodes
1
1
# Porblem Description\n\nGiven `n` binary tree nodes numbered from `0` to `n - 1`, represented by arrays `leftChild` and `rightChild` where each element corresponds to the `left` and `right` child of a node respectively, **determine** if the provided nodes **form** exactly one **valid** binary tree. \nA node with **no ...
93
**Tic-tac-toe** is played by two players `A` and `B` on a `3 x 3` grid. The rules of Tic-Tac-Toe are: * Players take turns placing characters into empty squares `' '`. * The first player `A` always places `'X'` characters, while the second player `B` always places `'O'` characters. * `'X'` and `'O'` characters a...
Find the parent of each node. A valid tree must have nodes with only one parent and exactly one node with no parent.
✅☑[C++/C/Java/Python/JavaScript] || 3 Approaches || Optimized || EXPLAINED🔥
validate-binary-tree-nodes
0
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### *Approach 1 (DFS)*\n1. `validateBinaryTreeNodes` is the main function that takes three parameters:\n\n - `n`: The total number of nodes in the tree.\n - `leftChild`: A vector representing the left child of each node. A...
2
You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree. If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child. ...
Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m).
✅☑[C++/C/Java/Python/JavaScript] || 3 Approaches || Optimized || EXPLAINED🔥
validate-binary-tree-nodes
0
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### *Approach 1 (DFS)*\n1. `validateBinaryTreeNodes` is the main function that takes three parameters:\n\n - `n`: The total number of nodes in the tree.\n - `leftChild`: A vector representing the left child of each node. A...
2
**Tic-tac-toe** is played by two players `A` and `B` on a `3 x 3` grid. The rules of Tic-Tac-Toe are: * Players take turns placing characters into empty squares `' '`. * The first player `A` always places `'X'` characters, while the second player `B` always places `'O'` characters. * `'X'` and `'O'` characters a...
Find the parent of each node. A valid tree must have nodes with only one parent and exactly one node with no parent.
Easy & Explained Graph (Dfs) Solution Python3 || Python Solution
validate-binary-tree-nodes
0
1
# Intuition- and Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nBasic intution to approach this problem would be like when only one binary tree is possible:\n- There should be a root node which means a node which only have max two outgoing edges not any incoming edge.\n- Should not have ...
1
You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree. If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child. ...
Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m).
Easy & Explained Graph (Dfs) Solution Python3 || Python Solution
validate-binary-tree-nodes
0
1
# Intuition- and Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nBasic intution to approach this problem would be like when only one binary tree is possible:\n- There should be a root node which means a node which only have max two outgoing edges not any incoming edge.\n- Should not have ...
1
**Tic-tac-toe** is played by two players `A` and `B` on a `3 x 3` grid. The rules of Tic-Tac-Toe are: * Players take turns placing characters into empty squares `' '`. * The first player `A` always places `'X'` characters, while the second player `B` always places `'O'` characters. * `'X'` and `'O'` characters a...
Find the parent of each node. A valid tree must have nodes with only one parent and exactly one node with no parent.
Python3 Solution
validate-binary-tree-nodes
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree. If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child. ...
Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m).
Python3 Solution
validate-binary-tree-nodes
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
**Tic-tac-toe** is played by two players `A` and `B` on a `3 x 3` grid. The rules of Tic-Tac-Toe are: * Players take turns placing characters into empty squares `' '`. * The first player `A` always places `'X'` characters, while the second player `B` always places `'O'` characters. * `'X'` and `'O'` characters a...
Find the parent of each node. A valid tree must have nodes with only one parent and exactly one node with no parent.
O(n), Shortest, nice and clear run through nodes with marking parents and roots.
validate-binary-tree-nodes
0
1
# Approach\nNice and clear single run through nodes with marking parents and roots. \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 valid...
1
You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree. If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child. ...
Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m).
O(n), Shortest, nice and clear run through nodes with marking parents and roots.
validate-binary-tree-nodes
0
1
# Approach\nNice and clear single run through nodes with marking parents and roots. \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 valid...
1
**Tic-tac-toe** is played by two players `A` and `B` on a `3 x 3` grid. The rules of Tic-Tac-Toe are: * Players take turns placing characters into empty squares `' '`. * The first player `A` always places `'X'` characters, while the second player `B` always places `'O'` characters. * `'X'` and `'O'` characters a...
Find the parent of each node. A valid tree must have nodes with only one parent and exactly one node with no parent.
✅ 80% 🔥Easy Solution 🔥With Explanation
validate-binary-tree-nodes
0
1
\n# Approach\n\nA binary tree is valid if it satisfies the following conditions:\n1. It has a single root node.\n2. Each non-root node has exactly one parent node.\n3. The tree is connected, meaning all nodes are reachable from the root.\n4. There are no cycles in the tree.\n\n# Complexity\n- Time complexity:\n O(n)...
1
You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree. If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child. ...
Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m).
✅ 80% 🔥Easy Solution 🔥With Explanation
validate-binary-tree-nodes
0
1
\n# Approach\n\nA binary tree is valid if it satisfies the following conditions:\n1. It has a single root node.\n2. Each non-root node has exactly one parent node.\n3. The tree is connected, meaning all nodes are reachable from the root.\n4. There are no cycles in the tree.\n\n# Complexity\n- Time complexity:\n O(n)...
1
**Tic-tac-toe** is played by two players `A` and `B` on a `3 x 3` grid. The rules of Tic-Tac-Toe are: * Players take turns placing characters into empty squares `' '`. * The first player `A` always places `'X'` characters, while the second player `B` always places `'O'` characters. * `'X'` and `'O'` characters a...
Find the parent of each node. A valid tree must have nodes with only one parent and exactly one node with no parent.
Python 3, topological sort
validate-binary-tree-nodes
0
1
# Intuition\nConsider the requirements needed for a valid binary tree\n\n1. At most two children for each node. (already satisfied)\n2. There is only one node which is the root node whose indgree is 0\n3. No cycle\n4. Indegree of each node is equal to 1.\n5. All nodes are reachable, which means the tree is fully connec...
1
You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree. If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child. ...
Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m).
Python 3, topological sort
validate-binary-tree-nodes
0
1
# Intuition\nConsider the requirements needed for a valid binary tree\n\n1. At most two children for each node. (already satisfied)\n2. There is only one node which is the root node whose indgree is 0\n3. No cycle\n4. Indegree of each node is equal to 1.\n5. All nodes are reachable, which means the tree is fully connec...
1
**Tic-tac-toe** is played by two players `A` and `B` on a `3 x 3` grid. The rules of Tic-Tac-Toe are: * Players take turns placing characters into empty squares `' '`. * The first player `A` always places `'X'` characters, while the second player `B` always places `'O'` characters. * `'X'` and `'O'` characters a...
Find the parent of each node. A valid tree must have nodes with only one parent and exactly one node with no parent.
[python3] find root and bfs
validate-binary-tree-nodes
0
1
Find the root of the tree first and then traverse. \nIf the visited node count == n and does not visit same node twice return True\n\n```\nclass Solution:\n def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:\n # construct a binary tree\n s = [0]\n vis...
1
You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree. If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child. ...
Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m).
[python3] find root and bfs
validate-binary-tree-nodes
0
1
Find the root of the tree first and then traverse. \nIf the visited node count == n and does not visit same node twice return True\n\n```\nclass Solution:\n def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:\n # construct a binary tree\n s = [0]\n vis...
1
**Tic-tac-toe** is played by two players `A` and `B` on a `3 x 3` grid. The rules of Tic-Tac-Toe are: * Players take turns placing characters into empty squares `' '`. * The first player `A` always places `'X'` characters, while the second player `B` always places `'O'` characters. * `'X'` and `'O'` characters a...
Find the parent of each node. A valid tree must have nodes with only one parent and exactly one node with no parent.
Greedy - beat 100% time / memory
closest-divisors
0
1
The greedy principle is used in the following two aspects, so that we can immediately return once we find a candidate `i` that meets the requirment:\n\n* Iterate candidates from `int(sqrt(num+2))` to `1`.\n* Check `num + 1` before `num + 2`. Because when a candidate `i` is valid for both `num + 1` and `num + 2`, The di...
10
Given an integer `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`. Return the two integers in any order. **Example 1:** **Input:** num = 8 **Output:** \[3,3\] **Explanation:** For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisor...
Let f(n) denote the probability of the n-th person getting correct seat in n-person case, then: f(1) = 1 (base case, trivial) f(2) = 1/2 (also trivial) Try to calculate f(3), f(4), and f(5) using the base cases. What if the value of them? f(i) for i >= 2 will also be 1/2. Try to proof why f(i) = 1/2 for i >= 2.
Greedy - beat 100% time / memory
closest-divisors
0
1
The greedy principle is used in the following two aspects, so that we can immediately return once we find a candidate `i` that meets the requirment:\n\n* Iterate candidates from `int(sqrt(num+2))` to `1`.\n* Check `num + 1` before `num + 2`. Because when a candidate `i` is valid for both `num + 1` and `num + 2`, The di...
10
Given two integers `tomatoSlices` and `cheeseSlices`. The ingredients of different burgers are as follows: * **Jumbo Burger:** `4` tomato slices and `1` cheese slice. * **Small Burger:** `2` Tomato slices and `1` cheese slice. Return `[total_jumbo, total_small]` so that the number of remaining `tomatoSlices` equa...
Find the divisors of n+1 and n+2. To find the divisors of a number, you only need to iterate to the square root of that number.
[Java/Python 3] Mod and Sqrt, O(sqrt(n)) code.
closest-divisors
1
1
```java\n public int[] closestDivisors(int num) {\n int[] res = {1, num + 1};\n int min = num;\n for (int n : new int[]{num + 1, num + 2}) {\n int d = (int)Math.floor(Math.sqrt(n)); \n while (d > 0 && n % d != 0) {--d; }\n if (min > n / d - d) {\n ...
8
Given an integer `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`. Return the two integers in any order. **Example 1:** **Input:** num = 8 **Output:** \[3,3\] **Explanation:** For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisor...
Let f(n) denote the probability of the n-th person getting correct seat in n-person case, then: f(1) = 1 (base case, trivial) f(2) = 1/2 (also trivial) Try to calculate f(3), f(4), and f(5) using the base cases. What if the value of them? f(i) for i >= 2 will also be 1/2. Try to proof why f(i) = 1/2 for i >= 2.
[Java/Python 3] Mod and Sqrt, O(sqrt(n)) code.
closest-divisors
1
1
```java\n public int[] closestDivisors(int num) {\n int[] res = {1, num + 1};\n int min = num;\n for (int n : new int[]{num + 1, num + 2}) {\n int d = (int)Math.floor(Math.sqrt(n)); \n while (d > 0 && n % d != 0) {--d; }\n if (min > n / d - d) {\n ...
8
Given two integers `tomatoSlices` and `cheeseSlices`. The ingredients of different burgers are as follows: * **Jumbo Burger:** `4` tomato slices and `1` cheese slice. * **Small Burger:** `2` Tomato slices and `1` cheese slice. Return `[total_jumbo, total_small]` so that the number of remaining `tomatoSlices` equa...
Find the divisors of n+1 and n+2. To find the divisors of a number, you only need to iterate to the square root of that number.
Beats 98% runtime and 71% memory
closest-divisors
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 `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`. Return the two integers in any order. **Example 1:** **Input:** num = 8 **Output:** \[3,3\] **Explanation:** For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisor...
Let f(n) denote the probability of the n-th person getting correct seat in n-person case, then: f(1) = 1 (base case, trivial) f(2) = 1/2 (also trivial) Try to calculate f(3), f(4), and f(5) using the base cases. What if the value of them? f(i) for i >= 2 will also be 1/2. Try to proof why f(i) = 1/2 for i >= 2.
Beats 98% runtime and 71% memory
closest-divisors
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 two integers `tomatoSlices` and `cheeseSlices`. The ingredients of different burgers are as follows: * **Jumbo Burger:** `4` tomato slices and `1` cheese slice. * **Small Burger:** `2` Tomato slices and `1` cheese slice. Return `[total_jumbo, total_small]` so that the number of remaining `tomatoSlices` equa...
Find the divisors of n+1 and n+2. To find the divisors of a number, you only need to iterate to the square root of that number.
Python3 Clean and Concise Solution
closest-divisors
0
1
\n\n# Code\n```\nclass Solution:\n def closestDivisors(self, num: int) -> List[int]:\n \n \n \n def f(x):\n local=[-1,-1]\n mn=inf\n \n for i in range(1,isqrt(x)+1):\n if x%i==0 and (x//i)-i < mn:\n local = [i, ...
0
Given an integer `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`. Return the two integers in any order. **Example 1:** **Input:** num = 8 **Output:** \[3,3\] **Explanation:** For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisor...
Let f(n) denote the probability of the n-th person getting correct seat in n-person case, then: f(1) = 1 (base case, trivial) f(2) = 1/2 (also trivial) Try to calculate f(3), f(4), and f(5) using the base cases. What if the value of them? f(i) for i >= 2 will also be 1/2. Try to proof why f(i) = 1/2 for i >= 2.
Python3 Clean and Concise Solution
closest-divisors
0
1
\n\n# Code\n```\nclass Solution:\n def closestDivisors(self, num: int) -> List[int]:\n \n \n \n def f(x):\n local=[-1,-1]\n mn=inf\n \n for i in range(1,isqrt(x)+1):\n if x%i==0 and (x//i)-i < mn:\n local = [i, ...
0
Given two integers `tomatoSlices` and `cheeseSlices`. The ingredients of different burgers are as follows: * **Jumbo Burger:** `4` tomato slices and `1` cheese slice. * **Small Burger:** `2` Tomato slices and `1` cheese slice. Return `[total_jumbo, total_small]` so that the number of remaining `tomatoSlices` equa...
Find the divisors of n+1 and n+2. To find the divisors of a number, you only need to iterate to the square root of that number.
100% beats time, easy solution python
closest-divisors
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe basic approach is to check for all divisors of the num+1 and num+2 of them the one with less absolute difference is the pair which we found first when traversing from sqrt of num+2,bcz as we go from 1 to sqrt of n, the difference betw...
0
Given an integer `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`. Return the two integers in any order. **Example 1:** **Input:** num = 8 **Output:** \[3,3\] **Explanation:** For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisor...
Let f(n) denote the probability of the n-th person getting correct seat in n-person case, then: f(1) = 1 (base case, trivial) f(2) = 1/2 (also trivial) Try to calculate f(3), f(4), and f(5) using the base cases. What if the value of them? f(i) for i >= 2 will also be 1/2. Try to proof why f(i) = 1/2 for i >= 2.
100% beats time, easy solution python
closest-divisors
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe basic approach is to check for all divisors of the num+1 and num+2 of them the one with less absolute difference is the pair which we found first when traversing from sqrt of num+2,bcz as we go from 1 to sqrt of n, the difference betw...
0
Given two integers `tomatoSlices` and `cheeseSlices`. The ingredients of different burgers are as follows: * **Jumbo Burger:** `4` tomato slices and `1` cheese slice. * **Small Burger:** `2` Tomato slices and `1` cheese slice. Return `[total_jumbo, total_small]` so that the number of remaining `tomatoSlices` equa...
Find the divisors of n+1 and n+2. To find the divisors of a number, you only need to iterate to the square root of that number.
python solution
closest-divisors
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 `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`. Return the two integers in any order. **Example 1:** **Input:** num = 8 **Output:** \[3,3\] **Explanation:** For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisor...
Let f(n) denote the probability of the n-th person getting correct seat in n-person case, then: f(1) = 1 (base case, trivial) f(2) = 1/2 (also trivial) Try to calculate f(3), f(4), and f(5) using the base cases. What if the value of them? f(i) for i >= 2 will also be 1/2. Try to proof why f(i) = 1/2 for i >= 2.
python solution
closest-divisors
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 two integers `tomatoSlices` and `cheeseSlices`. The ingredients of different burgers are as follows: * **Jumbo Burger:** `4` tomato slices and `1` cheese slice. * **Small Burger:** `2` Tomato slices and `1` cheese slice. Return `[total_jumbo, total_small]` so that the number of remaining `tomatoSlices` equa...
Find the divisors of n+1 and n+2. To find the divisors of a number, you only need to iterate to the square root of that number.
Python 3 Solution
closest-divisors
0
1
# Code\n```\nclass Solution:\n def closestDivisors(self, num: int) -> List[int]:\n\n for x in range(isqrt(num)+1,1,-1):\n if (num+1)%x == 0:\n return [(num + 1)//x,x]\n\n if (num+2)%x == 0:\n return [(num + 2)//x,x]\n\n \n```
0
Given an integer `num`, find the closest two integers in absolute difference whose product equals `num + 1` or `num + 2`. Return the two integers in any order. **Example 1:** **Input:** num = 8 **Output:** \[3,3\] **Explanation:** For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisor...
Let f(n) denote the probability of the n-th person getting correct seat in n-person case, then: f(1) = 1 (base case, trivial) f(2) = 1/2 (also trivial) Try to calculate f(3), f(4), and f(5) using the base cases. What if the value of them? f(i) for i >= 2 will also be 1/2. Try to proof why f(i) = 1/2 for i >= 2.
Python 3 Solution
closest-divisors
0
1
# Code\n```\nclass Solution:\n def closestDivisors(self, num: int) -> List[int]:\n\n for x in range(isqrt(num)+1,1,-1):\n if (num+1)%x == 0:\n return [(num + 1)//x,x]\n\n if (num+2)%x == 0:\n return [(num + 2)//x,x]\n\n \n```
0
Given two integers `tomatoSlices` and `cheeseSlices`. The ingredients of different burgers are as follows: * **Jumbo Burger:** `4` tomato slices and `1` cheese slice. * **Small Burger:** `2` Tomato slices and `1` cheese slice. Return `[total_jumbo, total_small]` so that the number of remaining `tomatoSlices` equa...
Find the divisors of n+1 and n+2. To find the divisors of a number, you only need to iterate to the square root of that number.
Python; 100% faster || T: O(n) S: O(1) || Dictionary + Math ||
largest-multiple-of-three
0
1
# Intuition\nMaximize the answer my choosing current available max number.\n\nAfter all numbers exhausted delete some numbers for correcting remainder.\n# Approach\nFirst find max number using counter dictionary. \n\nthen adjust it to multiple of 3 by\n\nNOTE :(For those who did not understood del2 call from del1): \nM...
2
Given an array of digits `digits`, return _the largest multiple of **three** that can be formed by concatenating some of the given digits in **any order**_. If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer ...
null
Python; 100% faster || T: O(n) S: O(1) || Dictionary + Math ||
largest-multiple-of-three
0
1
# Intuition\nMaximize the answer my choosing current available max number.\n\nAfter all numbers exhausted delete some numbers for correcting remainder.\n# Approach\nFirst find max number using counter dictionary. \n\nthen adjust it to multiple of 3 by\n\nNOTE :(For those who did not understood del2 call from del1): \nM...
2
Given a `m * n` matrix of ones and zeros, return how many **square** submatrices have all ones. **Example 1:** **Input:** matrix = \[ \[0,1,1,1\], \[1,1,1,1\], \[0,1,1,1\] \] **Output:** 15 **Explanation:** There are **10** squares of side 1. There are **4** squares of side 2. There is **1** square of side 3....
A number is a multiple of three if and only if its sum of digits is a multiple of three. Use dynamic programming. To find the maximum number, try to maximize the number of digits of the number. Sort the digits in descending order to find the maximum number.
[Python] O(n) Simple Bucket Sort with Explanation
largest-multiple-of-three
0
1
**Idea**\nAccording to the **3 divisibility rule** (proof: https://math.stackexchange.com/questions/341202/how-to-prove-the-divisibility-rule-for-3-casting-out-threes).\nOur goal is to find **the maximum number of digits whose sum is a multiple of 3**.\n\nWe categorize all the input digits into 3 category. \n- `{0, 3, ...
12
Given an array of digits `digits`, return _the largest multiple of **three** that can be formed by concatenating some of the given digits in **any order**_. If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer ...
null
[Python] O(n) Simple Bucket Sort with Explanation
largest-multiple-of-three
0
1
**Idea**\nAccording to the **3 divisibility rule** (proof: https://math.stackexchange.com/questions/341202/how-to-prove-the-divisibility-rule-for-3-casting-out-threes).\nOur goal is to find **the maximum number of digits whose sum is a multiple of 3**.\n\nWe categorize all the input digits into 3 category. \n- `{0, 3, ...
12
Given a `m * n` matrix of ones and zeros, return how many **square** submatrices have all ones. **Example 1:** **Input:** matrix = \[ \[0,1,1,1\], \[1,1,1,1\], \[0,1,1,1\] \] **Output:** 15 **Explanation:** There are **10** squares of side 1. There are **4** squares of side 2. There is **1** square of side 3....
A number is a multiple of three if and only if its sum of digits is a multiple of three. Use dynamic programming. To find the maximum number, try to maximize the number of digits of the number. Sort the digits in descending order to find the maximum number.
Whatever Jutsu Solution
largest-multiple-of-three
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$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $...
0
Given an array of digits `digits`, return _the largest multiple of **three** that can be formed by concatenating some of the given digits in **any order**_. If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer ...
null
Whatever Jutsu Solution
largest-multiple-of-three
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$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $...
0
Given a `m * n` matrix of ones and zeros, return how many **square** submatrices have all ones. **Example 1:** **Input:** matrix = \[ \[0,1,1,1\], \[1,1,1,1\], \[0,1,1,1\] \] **Output:** 15 **Explanation:** There are **10** squares of side 1. There are **4** squares of side 2. There is **1** square of side 3....
A number is a multiple of three if and only if its sum of digits is a multiple of three. Use dynamic programming. To find the maximum number, try to maximize the number of digits of the number. Sort the digits in descending order to find the maximum number.
Over*simplification eFINALITYpi:
largest-multiple-of-three
0
1
```\nclass Solution:\n def largestMultipleOfThree(self, d: List[int]) -> str:\n for i in [c:=Counter(d),o:=sum(d)%3,1,2][2:]*(0<o):\n if o and len(z:=list(islice(chain(*([e]*min(c[e],i) for e in range(i*o%3,9,3))),i)))==i:\n for e in z:c[e]-=1;o=0\n return \'\' if o else \'0\'...
0
Given an array of digits `digits`, return _the largest multiple of **three** that can be formed by concatenating some of the given digits in **any order**_. If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer ...
null
Over*simplification eFINALITYpi:
largest-multiple-of-three
0
1
```\nclass Solution:\n def largestMultipleOfThree(self, d: List[int]) -> str:\n for i in [c:=Counter(d),o:=sum(d)%3,1,2][2:]*(0<o):\n if o and len(z:=list(islice(chain(*([e]*min(c[e],i) for e in range(i*o%3,9,3))),i)))==i:\n for e in z:c[e]-=1;o=0\n return \'\' if o else \'0\'...
0
Given a `m * n` matrix of ones and zeros, return how many **square** submatrices have all ones. **Example 1:** **Input:** matrix = \[ \[0,1,1,1\], \[1,1,1,1\], \[0,1,1,1\] \] **Output:** 15 **Explanation:** There are **10** squares of side 1. There are **4** squares of side 2. There is **1** square of side 3....
A number is a multiple of three if and only if its sum of digits is a multiple of three. Use dynamic programming. To find the maximum number, try to maximize the number of digits of the number. Sort the digits in descending order to find the maximum number.
Python3||DP
largest-multiple-of-three
0
1
# Intuition\n- Intituion is that find the largest sum in the array divisble by three and try to trace it\n\n# Approach\n- DP\n\n# Complexity\n- Time complexity:\n- O(N^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def largestMultipleOfThree(self, ...
0
Given an array of digits `digits`, return _the largest multiple of **three** that can be formed by concatenating some of the given digits in **any order**_. If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer ...
null
Python3||DP
largest-multiple-of-three
0
1
# Intuition\n- Intituion is that find the largest sum in the array divisble by three and try to trace it\n\n# Approach\n- DP\n\n# Complexity\n- Time complexity:\n- O(N^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def largestMultipleOfThree(self, ...
0
Given a `m * n` matrix of ones and zeros, return how many **square** submatrices have all ones. **Example 1:** **Input:** matrix = \[ \[0,1,1,1\], \[1,1,1,1\], \[0,1,1,1\] \] **Output:** 15 **Explanation:** There are **10** squares of side 1. There are **4** squares of side 2. There is **1** square of side 3....
A number is a multiple of three if and only if its sum of digits is a multiple of three. Use dynamic programming. To find the maximum number, try to maximize the number of digits of the number. Sort the digits in descending order to find the maximum number.
Python: Got past TLE with hack
largest-multiple-of-three
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAt first, I tried the approach suggested by the Hint: Use dynamic\nprogramming to find the solution. However, even using ```lru_cache(None)``` to accelerate the DP, I was still getting Time Limit Exceeded. I then came up with a hack th...
0
Given an array of digits `digits`, return _the largest multiple of **three** that can be formed by concatenating some of the given digits in **any order**_. If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer ...
null
Python: Got past TLE with hack
largest-multiple-of-three
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAt first, I tried the approach suggested by the Hint: Use dynamic\nprogramming to find the solution. However, even using ```lru_cache(None)``` to accelerate the DP, I was still getting Time Limit Exceeded. I then came up with a hack th...
0
Given a `m * n` matrix of ones and zeros, return how many **square** submatrices have all ones. **Example 1:** **Input:** matrix = \[ \[0,1,1,1\], \[1,1,1,1\], \[0,1,1,1\] \] **Output:** 15 **Explanation:** There are **10** squares of side 1. There are **4** squares of side 2. There is **1** square of side 3....
A number is a multiple of three if and only if its sum of digits is a multiple of three. Use dynamic programming. To find the maximum number, try to maximize the number of digits of the number. Sort the digits in descending order to find the maximum number.
Solution
largest-multiple-of-three
0
1
To find the largest multiple of three, we need to consider the following cases:\n\n1. If the sum of all digits is divisible by 3, we can use all the digits to form the largest multiple of three. In this case, we should sort the digits in non-ascending order and return the result as a string.\n\n2. If the sum of all dig...
0
Given an array of digits `digits`, return _the largest multiple of **three** that can be formed by concatenating some of the given digits in **any order**_. If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer ...
null
Solution
largest-multiple-of-three
0
1
To find the largest multiple of three, we need to consider the following cases:\n\n1. If the sum of all digits is divisible by 3, we can use all the digits to form the largest multiple of three. In this case, we should sort the digits in non-ascending order and return the result as a string.\n\n2. If the sum of all dig...
0
Given a `m * n` matrix of ones and zeros, return how many **square** submatrices have all ones. **Example 1:** **Input:** matrix = \[ \[0,1,1,1\], \[1,1,1,1\], \[0,1,1,1\] \] **Output:** 15 **Explanation:** There are **10** squares of side 1. There are **4** squares of side 2. There is **1** square of side 3....
A number is a multiple of three if and only if its sum of digits is a multiple of three. Use dynamic programming. To find the maximum number, try to maximize the number of digits of the number. Sort the digits in descending order to find the maximum number.
Python solution faster than 99% with detailed explanation
largest-multiple-of-three
0
1
A number that is a multiple of three meets the property that the sum of all digits is a multiple of three. \nThus, we can try to find the answer from the three options from the n input digits in the following order: \n1. The answer is composed by all the n digits if the sum of all the n digits is a multiple of three.\n...
0
Given an array of digits `digits`, return _the largest multiple of **three** that can be formed by concatenating some of the given digits in **any order**_. If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer ...
null
Python solution faster than 99% with detailed explanation
largest-multiple-of-three
0
1
A number that is a multiple of three meets the property that the sum of all digits is a multiple of three. \nThus, we can try to find the answer from the three options from the n input digits in the following order: \n1. The answer is composed by all the n digits if the sum of all the n digits is a multiple of three.\n...
0
Given a `m * n` matrix of ones and zeros, return how many **square** submatrices have all ones. **Example 1:** **Input:** matrix = \[ \[0,1,1,1\], \[1,1,1,1\], \[0,1,1,1\] \] **Output:** 15 **Explanation:** There are **10** squares of side 1. There are **4** squares of side 2. There is **1** square of side 3....
A number is a multiple of three if and only if its sum of digits is a multiple of three. Use dynamic programming. To find the maximum number, try to maximize the number of digits of the number. Sort the digits in descending order to find the maximum number.
Python DP
largest-multiple-of-three
0
1
```\nclass Solution:\n def largestMultipleOfThree(self, d: List[int]) -> str:\n dp = [-1,-1,-1]\n for e in sorted(d, reverse=True):\n for a in dp+[0]:\n y = a * 10 + e\n dp[y%3] = max(dp[y%3], y)\n return str(dp[0]) if dp[0] >= 0 else ""\n```
0
Given an array of digits `digits`, return _the largest multiple of **three** that can be formed by concatenating some of the given digits in **any order**_. If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer ...
null
Python DP
largest-multiple-of-three
0
1
```\nclass Solution:\n def largestMultipleOfThree(self, d: List[int]) -> str:\n dp = [-1,-1,-1]\n for e in sorted(d, reverse=True):\n for a in dp+[0]:\n y = a * 10 + e\n dp[y%3] = max(dp[y%3], y)\n return str(dp[0]) if dp[0] >= 0 else ""\n```
0
Given a `m * n` matrix of ones and zeros, return how many **square** submatrices have all ones. **Example 1:** **Input:** matrix = \[ \[0,1,1,1\], \[1,1,1,1\], \[0,1,1,1\] \] **Output:** 15 **Explanation:** There are **10** squares of side 1. There are **4** squares of side 2. There is **1** square of side 3....
A number is a multiple of three if and only if its sum of digits is a multiple of three. Use dynamic programming. To find the maximum number, try to maximize the number of digits of the number. Sort the digits in descending order to find the maximum number.
Sorting Arrays in C++ and Python3✅
how-many-numbers-are-smaller-than-the-current-number
0
1
# Code\n```Python3 []\nclass Solution:\n def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:\n test_list = sorted(nums)\n answer = []\n for i in nums:\n answer.append(test_list.index(i))\n return answer\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> ...
2
Given the array `nums`, for each `nums[i]` find out how many numbers in the array are smaller than it. That is, for each `nums[i]` you have to count the number of valid `j's` such that `j != i` **and** `nums[j] < nums[i]`. Return the answer in an array. **Example 1:** **Input:** nums = \[8,1,2,2,3\] **Output:** \[4,...
null
Sorting Arrays in C++ and Python3✅
how-many-numbers-are-smaller-than-the-current-number
0
1
# Code\n```Python3 []\nclass Solution:\n def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:\n test_list = sorted(nums)\n answer = []\n for i in nums:\n answer.append(test_list.index(i))\n return answer\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> ...
2
You are given an integer array `bloomDay`, an integer `m` and an integer `k`. You want to make `m` bouquets. To make a bouquet, you need to use `k` **adjacent flowers** from the garden. The garden consists of `n` flowers, the `ith` flower will bloom in the `bloomDay[i]` and then can be used in **exactly one** bouquet...
Brute force for each array element. In order to improve the time complexity, we can sort the array and get the answer for each array element.
Python 3 -> 91.11% faster. 52ms time. Explanation added
how-many-numbers-are-smaller-than-the-current-number
0
1
**Suggestions to make it better are always welcomed.**\n\n**2 possible solutions:**\n1. For every i element, iterate the list with j as index. If i!=j and nums[j]<nums[i], we can update the count for that number. Time: O(n2). Space: O(1)\n2. This is optimal solution. We can sort the list and store in another temp list....
201
Given the array `nums`, for each `nums[i]` find out how many numbers in the array are smaller than it. That is, for each `nums[i]` you have to count the number of valid `j's` such that `j != i` **and** `nums[j] < nums[i]`. Return the answer in an array. **Example 1:** **Input:** nums = \[8,1,2,2,3\] **Output:** \[4,...
null