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 |
|---|---|---|---|---|---|---|---|
Frequency Distribution - Clean code | maximum-equal-frequency | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe question states\n> every number that has appeared in it will have the same number of occurrences\n\nThis is a clear sign that at the core of the problem we need to keep track of the frequency of the frequencies of each number (call th... | 0 | Given two numbers, `hour` and `minutes`, return _the smaller angle (in degrees) formed between the_ `hour` _and the_ `minute` _hand_.
Answers within `10-5` of the actual value will be accepted as correct.
**Example 1:**
**Input:** hour = 12, minutes = 30
**Output:** 165
**Example 2:**
**Input:** hour = 3, minutes ... | Keep track of the min and max frequencies. The number to be eliminated must have a frequency of 1, same as the others or the same +1. |
Python (Simple Hashmap) | maximum-equal-frequency | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given an array `nums` of positive integers, return the longest possible length of an array prefix of `nums`, such that it is possible to remove **exactly one** element from this prefix so that every number that has appeared in it will have the same number of occurrences.
If after removing one element there are no rema... | Use dynamic programming. Let dp[i][j] be the answer for the first i rows such that column j is chosen from row i. Use the concept of cumulative array to optimize the complexity of the solution. |
Python (Simple Hashmap) | maximum-equal-frequency | 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 numbers, `hour` and `minutes`, return _the smaller angle (in degrees) formed between the_ `hour` _and the_ `minute` _hand_.
Answers within `10-5` of the actual value will be accepted as correct.
**Example 1:**
**Input:** hour = 12, minutes = 30
**Output:** 165
**Example 2:**
**Input:** hour = 3, minutes ... | Keep track of the min and max frequencies. The number to be eliminated must have a frequency of 1, same as the others or the same +1. |
Python3: Count collections | maximum-equal-frequency | 0 | 1 | The basic idea is to first count the occurence of each number in `nums`.\nThen, count the counts--i.e. count the occurrence groups. \nThe solution must be 1 of a few scenarios (there were more trivial scenarios then I thought - leading to bad submissions).\nIf the count of counts is not one such scenario: `nums.pop... | 3 | Given an array `nums` of positive integers, return the longest possible length of an array prefix of `nums`, such that it is possible to remove **exactly one** element from this prefix so that every number that has appeared in it will have the same number of occurrences.
If after removing one element there are no rema... | Use dynamic programming. Let dp[i][j] be the answer for the first i rows such that column j is chosen from row i. Use the concept of cumulative array to optimize the complexity of the solution. |
Python3: Count collections | maximum-equal-frequency | 0 | 1 | The basic idea is to first count the occurence of each number in `nums`.\nThen, count the counts--i.e. count the occurrence groups. \nThe solution must be 1 of a few scenarios (there were more trivial scenarios then I thought - leading to bad submissions).\nIf the count of counts is not one such scenario: `nums.pop... | 3 | Given two numbers, `hour` and `minutes`, return _the smaller angle (in degrees) formed between the_ `hour` _and the_ `minute` _hand_.
Answers within `10-5` of the actual value will be accepted as correct.
**Example 1:**
**Input:** hour = 12, minutes = 30
**Output:** 165
**Example 2:**
**Input:** hour = 3, minutes ... | Keep track of the min and max frequencies. The number to be eliminated must have a frequency of 1, same as the others or the same +1. |
[Python] | Left-right for even; right-left for odd philosophers | the-dining-philosophers | 0 | 1 | # Intuition\nCreate a Lock for each fork. Each philosopher tries to acquire 2 forks adjacent to him, before eating\n\nIf all philosophers take the fork to the left first, there can be a deadlock, when all of them got only 1 fork.\n\n# Approach\nTo resolve the deadlock, make even philosopers take left first, then right.... | 3 | Given an array of integers `arr` and an integer `d`. In one step you can jump from index `i` to index:
* `i + x` where: `i + x < arr.length` and `0 < x <= d`.
* `i - x` where: `i - x >= 0` and `0 < x <= d`.
In addition, you can only jump from index `i` to index `j` if `arr[i] > arr[j]` and `arr[i] > arr[k]` for a... | null |
Simple python solution using lock ordering | the-dining-philosophers | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTake locks in sorted order. Philosopher 0 must take fork 0 before he takes fork 1, this means philosopher 4 takes fork 0 before he takes fork 4.\n\nSo only one of them will take the fork 0 and the other will wait. Since we have to have on... | 0 | Given an array of integers `arr` and an integer `d`. In one step you can jump from index `i` to index:
* `i + x` where: `i + x < arr.length` and `0 < x <= d`.
* `i - x` where: `i - x >= 0` and `0 < x <= d`.
In addition, you can only jump from index `i` to index `j` if `arr[i] > arr[j]` and `arr[i] > arr[k]` for a... | null |
Python 4 locks() with some explanation | the-dining-philosophers | 0 | 1 | Beats 100.00%\n\n# Code\n```\nfrom threading import Lock\n\nclass DiningPhilosophers:\n\n # class variables single copy exists\n even=Lock()\n seam=[Lock() for _ in range(5)]\n\n # call the functions directly to execute, for example, eat()\n def wantsToEat(self,\n i: int,\n ... | 0 | Given an array of integers `arr` and an integer `d`. In one step you can jump from index `i` to index:
* `i + x` where: `i + x < arr.length` and `0 < x <= d`.
* `i - x` where: `i - x >= 0` and `0 < x <= d`.
In addition, you can only jump from index `i` to index `j` if `arr[i] > arr[j]` and `arr[i] > arr[k]` for a... | null |
Basic solution | airplane-seat-assignment-probability | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nHe will get his seat or he will lose his seat.\n\n# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n return 1/2 ... | 0 | `n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
* Take their own seat if it is still available, and
* Pick other seats randomly when they find their seat occupied
Return _the probability th... | For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap. |
Basic solution | airplane-seat-assignment-probability | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nHe will get his seat or he will lose his seat.\n\n# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n return 1/2 ... | 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. |
Airplane seat assignment probability | airplane-seat-assignment-probability | 0 | 1 | # Intuition\n\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 | `n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
* Take their own seat if it is still available, and
* Pick other seats randomly when they find their seat occupied
Return _the probability th... | For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap. |
Airplane seat assignment probability | airplane-seat-assignment-probability | 0 | 1 | # Intuition\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ ... | 1 | Given 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. |
Middle school solution, Just counting cases. | airplane-seat-assignment-probability | 0 | 1 | Let n = 10\n\nTake one case for example: \n\nFirst person took **seat 3**, third person then sit on **seat 7**, and the seventh person sit on **seat 1**. \n\nThen we write down the sequence **[3, 7, 1]** to represent what just happened.\n\nNow every case corresponds to a sequence and vice versa. These sequence must be:... | 1 | `n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
* Take their own seat if it is still available, and
* Pick other seats randomly when they find their seat occupied
Return _the probability th... | For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap. |
Middle school solution, Just counting cases. | airplane-seat-assignment-probability | 0 | 1 | Let n = 10\n\nTake one case for example: \n\nFirst person took **seat 3**, third person then sit on **seat 7**, and the seventh person sit on **seat 1**. \n\nThen we write down the sequence **[3, 7, 1]** to represent what just happened.\n\nNow every case corresponds to a sequence and vice versa. These sequence must be:... | 1 | 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. |
0.5 if n > 1 else 1 Math Proof | airplane-seat-assignment-probability | 0 | 1 | # Math Solution\nLet $S = \\{p_1, p_2, p_3, p_4, \\cdots , p_n\\}$ be a set of $n$ person where $p_1$ picks a random seat.\nLet $p(n)$ = probability of $p_n$ getting their seat.\n\n## Base Cases\n$S = \\{p_1\\}$, $p(1) = 1$\n$S = \\{p_1, p_2\\}$, $p(2) = 0.5$\n\n## For $n > 2$\nIf $p_1$ takes their correct seat then al... | 4 | `n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
* Take their own seat if it is still available, and
* Pick other seats randomly when they find their seat occupied
Return _the probability th... | For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap. |
0.5 if n > 1 else 1 Math Proof | airplane-seat-assignment-probability | 0 | 1 | # Math Solution\nLet $S = \\{p_1, p_2, p_3, p_4, \\cdots , p_n\\}$ be a set of $n$ person where $p_1$ picks a random seat.\nLet $p(n)$ = probability of $p_n$ getting their seat.\n\n## Base Cases\n$S = \\{p_1\\}$, $p(1) = 1$\n$S = \\{p_1, p_2\\}$, $p(2) = 0.5$\n\n## For $n > 2$\nIf $p_1$ takes their correct seat then al... | 4 | 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 DP with explanation | airplane-seat-assignment-probability | 0 | 1 | Basically, we model dp[n] = P(n). We start with base cases dp[1] = 1.0, and dp[2] = 0.5.\nWhat is dp[3]? If n = 3, and first person picks his own seat (1/n chance), then we get 1/n * P(1). if the first person picks the 2nd seat (1/n chance), then the second person has to pick between two seats, so we get 1/n * P(2). Th... | 12 | `n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
* Take their own seat if it is still available, and
* Pick other seats randomly when they find their seat occupied
Return _the probability th... | For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap. |
Python3 DP with explanation | airplane-seat-assignment-probability | 0 | 1 | Basically, we model dp[n] = P(n). We start with base cases dp[1] = 1.0, and dp[2] = 0.5.\nWhat is dp[3]? If n = 3, and first person picks his own seat (1/n chance), then we get 1/n * P(1). if the first person picks the 2nd seat (1/n chance), then the second person has to pick between two seats, so we get 1/n * P(2). Th... | 12 | 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. |
1 line | airplane-seat-assignment-probability | 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 | `n` passengers board an airplane with exactly `n` seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
* Take their own seat if it is still available, and
* Pick other seats randomly when they find their seat occupied
Return _the probability th... | For each domino j, find the number of dominoes you've already seen (dominoes i with i < j) that are equivalent. You can keep track of what you've seen using a hashmap. |
1 line | airplane-seat-assignment-probability | 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. |
1232. Check If It Is a Straight Line Solution in Python | check-if-it-is-a-straight-line | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nHere\'s a breakdown of how the code works:\n\n1. It starts by getting the number of coordinates in the input list, denoted as n.\n\n2. It then extracts the x and y coordinates of the first two points (the 0th and 1st elements) from the input list.\n\n... | 1 | You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane.
**Example 1:**
**Input:** coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\]
**Output:** true
**Example 2:**
**Input:** coo... | If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value. |
1232. Check If It Is a Straight Line Solution in Python | check-if-it-is-a-straight-line | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nHere\'s a breakdown of how the code works:\n\n1. It starts by getting the number of coordinates in the input list, denoted as n.\n\n2. It then extracts the x and y coordinates of the first two points (the 0th and 1st elements) from the input list.\n\n... | 1 | Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character.
Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the s... | If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity. |
Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand | check-if-it-is-a-straight-line | 1 | 1 | # !! BIG ANNOUNCEMENT !!\r\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. This is only for the first 10,000 Subscribers. **DON\'T FORGET** to Subscribe\r\n\r\n# Se... | 44 | You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane.
**Example 1:**
**Input:** coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\]
**Output:** true
**Example 2:**
**Input:** coo... | If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value. |
Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand | check-if-it-is-a-straight-line | 1 | 1 | # !! BIG ANNOUNCEMENT !!\r\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. This is only for the first 10,000 Subscribers. **DON\'T FORGET** to Subscribe\r\n\r\n# Se... | 44 | Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character.
Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the s... | If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity. |
[Java/Python 3] check slopes, short code w/ explanation and analysis. | check-if-it-is-a-straight-line | 1 | 1 | The slope for a line through any 2 points `(x0, y0)` and `(x1, y1)` is `(y1 - y0) / (x1 - x0)`; Therefore, for any given 3 points (denote the 3rd point as `(x, y)`), if they are in a straight line, the slopes of the lines from the 3rd point to the 2nd point and the 2nd point to the 1st point must be equal:\n```\n(y - y... | 306 | You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane.
**Example 1:**
**Input:** coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\]
**Output:** true
**Example 2:**
**Input:** coo... | If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value. |
[Java/Python 3] check slopes, short code w/ explanation and analysis. | check-if-it-is-a-straight-line | 1 | 1 | The slope for a line through any 2 points `(x0, y0)` and `(x1, y1)` is `(y1 - y0) / (x1 - x0)`; Therefore, for any given 3 points (denote the 3rd point as `(x, y)`), if they are in a straight line, the slopes of the lines from the 3rd point to the 2nd point and the 2nd point to the 1st point must be equal:\n```\n(y - y... | 306 | Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character.
Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the s... | If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity. |
Python Elegant & Short | 3-Lines | check-if-it-is-a-straight-line | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def checkStraightLine(self, coordinates: List[List[int]]) -> bool:\n x0, y0 = coordinates.pop()\n x1, y1 = coordinates.pop()\n return all((x1 - x0) * (y - y1) == (x - x1) * (y1 - y0) for x, ... | 6 | You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane.
**Example 1:**
**Input:** coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\]
**Output:** true
**Example 2:**
**Input:** coo... | If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value. |
Python Elegant & Short | 3-Lines | check-if-it-is-a-straight-line | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def checkStraightLine(self, coordinates: List[List[int]]) -> bool:\n x0, y0 = coordinates.pop()\n x1, y1 = coordinates.pop()\n return all((x1 - x0) * (y - y1) == (x - x1) * (y1 - y0) for x, ... | 6 | Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character.
Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the s... | If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity. |
[Java] [Python3] [CPP] | Simple code with explanation | 100% fast | O(1) space | check-if-it-is-a-straight-line | 1 | 1 | \n**The point is if we take points p1(x, y), p2(x1, y1), p3(x3, y3), slopes of any two pairs is same then p1, p2, p3 lies on same line.\n slope from p1 and p2 is y - y1 / x - x1\n slope from p2 and p3 is y2 - y1 / x2 - x1\nif these two slopes equal, then p1, p2, p3 lies on same line.**\n\n**IF YOU HAVE ANY ... | 205 | You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane.
**Example 1:**
**Input:** coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\]
**Output:** true
**Example 2:**
**Input:** coo... | If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value. |
[Java] [Python3] [CPP] | Simple code with explanation | 100% fast | O(1) space | check-if-it-is-a-straight-line | 1 | 1 | \n**The point is if we take points p1(x, y), p2(x1, y1), p3(x3, y3), slopes of any two pairs is same then p1, p2, p3 lies on same line.\n slope from p1 and p2 is y - y1 / x - x1\n slope from p2 and p3 is y2 - y1 / x2 - x1\nif these two slopes equal, then p1, p2, p3 lies on same line.**\n\n**IF YOU HAVE ANY ... | 205 | Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character.
Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the s... | If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity. |
2 passes, Python trie solution (no sorting) | remove-sub-folders-from-the-filesystem | 0 | 1 | \n```\nclass TrieNode:\n def __init__(self):\n self.children = collections.defaultdict(TrieNode)\n self.end = False\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n\n def insert(self, path):\n curr = self.root\n for i in range(len(path)):\n curr = cu... | 0 | Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**.
If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of it.
The format of a path is one or more concatenated strings of the form: `'/... | Use divide and conquer technique. Divide the query rectangle into 4 rectangles. Use recursion to continue with the rectangles that has ships only. |
Python trie backtracking solution | remove-sub-folders-from-the-filesystem | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nConsider the folder names and build a trie (prefix tree) out of it. Traverse the trie to find the valid paths only\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Split by `/` and consider the characters only\n- ... | 0 | Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**.
If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of it.
The format of a path is one or more concatenated strings of the form: `'/... | Use divide and conquer technique. Divide the query rectangle into 4 rectangles. Use recursion to continue with the rectangles that has ships only. |
very simple solution using only one for | remove-sub-folders-from-the-filesystem | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**.
If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of it.
The format of a path is one or more concatenated strings of the form: `'/... | Use divide and conquer technique. Divide the query rectangle into 4 rectangles. Use recursion to continue with the rectangles that has ships only. |
Easy to understand Python3 solution | remove-sub-folders-from-the-filesystem | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**.
If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of it.
The format of a path is one or more concatenated strings of the form: `'/... | Use divide and conquer technique. Divide the query rectangle into 4 rectangles. Use recursion to continue with the rectangles that has ships only. |
Trie, DFS | remove-sub-folders-from-the-filesystem | 0 | 1 | \n# Code\n```\nclass Trie:\n\n def __init__(self):\n self.dic = dict()\n \n def add(self, word):\n l = word.split(\'/\')\n cur = self.dic\n for ch in l:\n if ch not in cur:\n cur[ch] = {}\n cur = cur[ch]\n cur[\'*\'] = \'\'\n \n def ... | 0 | Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**.
If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of it.
The format of a path is one or more concatenated strings of the form: `'/... | Use divide and conquer technique. Divide the query rectangle into 4 rectangles. Use recursion to continue with the rectangles that has ships only. |
[Python3] Good enough | remove-sub-folders-from-the-filesystem | 0 | 1 | ``` Python3 []\nclass Solution:\n def removeSubfolders(self, folder: List[str]) -> List[str]:\n folder.sort(key=lambda x: len(x))\n seen = set()\n final = []\n\n for x in folder:\n for i in range(2, len(x.split(\'/\'))):\n if tuple(x.split(\'/\')[1:i]) in seen:\n... | 0 | Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**.
If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of it.
The format of a path is one or more concatenated strings of the form: `'/... | Use divide and conquer technique. Divide the query rectangle into 4 rectangles. Use recursion to continue with the rectangles that has ships only. |
Python simply solution beats 97.80% | remove-sub-folders-from-the-filesystem | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O... | 0 | Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**.
If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of it.
The format of a path is one or more concatenated strings of the form: `'/... | Use divide and conquer technique. Divide the query rectangle into 4 rectangles. Use recursion to continue with the rectangles that has ships only. |
[Python3] sliding window with explanation | replace-the-substring-for-balanced-string | 0 | 1 | This problem can be split into two small problems:\n1. find out which letters have extra numbers in the string\n2. find out the shortest substring that contains those extra letters\n\nOnce this gets sorted out the solution gonna be pretty straightforward.\nComplexity: time O(n) space O(1)\n\n```\nclass Solution:\n d... | 11 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** othe... | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
[Python3] sliding window with explanation | replace-the-substring-for-balanced-string | 0 | 1 | This problem can be split into two small problems:\n1. find out which letters have extra numbers in the string\n2. find out the shortest substring that contains those extra letters\n\nOnce this gets sorted out the solution gonna be pretty straightforward.\nComplexity: time O(n) space O(1)\n\n```\nclass Solution:\n d... | 11 | Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the ma... | Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough. |
Python O(n) with no sliding window | replace-the-substring-for-balanced-string | 0 | 1 | ```\n\nfrom collections import Counter,defaultdict\n\nclass Solution:\n def balancedString(self, s: str) -> int:\n extra = Counter(s) - Counter({a: len(s)//4 for a in \'QWER\'})\n if not extra:\n return 0\n \n ans = len(s)\n indices = defaultdict(list)\n for i, a ... | 1 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** othe... | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
Python O(n) with no sliding window | replace-the-substring-for-balanced-string | 0 | 1 | ```\n\nfrom collections import Counter,defaultdict\n\nclass Solution:\n def balancedString(self, s: str) -> int:\n extra = Counter(s) - Counter({a: len(s)//4 for a in \'QWER\'})\n if not extra:\n return 0\n \n ans = len(s)\n indices = defaultdict(list)\n for i, a ... | 1 | Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the ma... | Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough. |
Python 3: Four Queues, Sliding Window | replace-the-substring-for-balanced-string | 0 | 1 | # Intuition\n\nThis took me quite a while to figure out. We can infer the trick is probably some kind of slidng window, but getting the window logic right is tricky.\n\nEventually what I realized was\n* we have `N` elements, divisible by four\n* we want `T = N//4` copies of each character\n* we can change any character... | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** othe... | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
Python 3: Four Queues, Sliding Window | replace-the-substring-for-balanced-string | 0 | 1 | # Intuition\n\nThis took me quite a while to figure out. We can infer the trick is probably some kind of slidng window, but getting the window logic right is tricky.\n\nEventually what I realized was\n* we have `N` elements, divisible by four\n* we want `T = N//4` copies of each character\n* we can change any character... | 0 | Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the ma... | Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough. |
💡💡 Neatly coded sliding window solution in python3 | replace-the-substring-for-balanced-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problme is a subproblem of 76. Minimum Window Substring - https://leetcode.com/problems/minimum-window-substring/solutions/4392528/neatly-coded-sliding-window-solution-in-python3/\nthe only difference being that here, we are also supp... | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** othe... | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
💡💡 Neatly coded sliding window solution in python3 | replace-the-substring-for-balanced-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problme is a subproblem of 76. Minimum Window Substring - https://leetcode.com/problems/minimum-window-substring/solutions/4392528/neatly-coded-sliding-window-solution-in-python3/\nthe only difference being that here, we are also supp... | 0 | Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the ma... | Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough. |
cleared code | replace-the-substring-for-balanced-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** othe... | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
cleared code | replace-the-substring-for-balanced-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the ma... | Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough. |
sliding window[python] || O(N) Time | replace-the-substring-for-balanced-string | 0 | 1 | # Intuition\n- First thing to be noticed is every element should appear exactly n/4 times.so n will be a multiple of 4\n- But some char will appear more than n/4 supresing the other \n- now we have to find the smallest subarray which supreses other char\n\n\n<!-- Describe your first thoughts on how to solve this proble... | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** othe... | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
sliding window[python] || O(N) Time | replace-the-substring-for-balanced-string | 0 | 1 | # Intuition\n- First thing to be noticed is every element should appear exactly n/4 times.so n will be a multiple of 4\n- But some char will appear more than n/4 supresing the other \n- now we have to find the smallest subarray which supreses other char\n\n\n<!-- Describe your first thoughts on how to solve this proble... | 0 | Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the ma... | Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough. |
Python3 Clean Sliding Window Solution | replace-the-substring-for-balanced-string | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def balancedString(self, s: str) -> int:\n \n \n extra=""\n \n actual=len(s)//4\n count=Counter(s)\n \n for ch in count:\n if count[ch]>actual:\n extra+=(count[ch]-actual)*ch\n \n \n ... | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** othe... | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
Python3 Clean Sliding Window Solution | replace-the-substring-for-balanced-string | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def balancedString(self, s: str) -> int:\n \n \n extra=""\n \n actual=len(s)//4\n count=Counter(s)\n \n for ch in count:\n if count[ch]>actual:\n extra+=(count[ch]-actual)*ch\n \n \n ... | 0 | Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the ma... | Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough. |
Python Medium | replace-the-substring-for-balanced-string | 0 | 1 | ```\nclass Solution:\n def balancedString(self, s: str) -> int:\n M = len(s) // 4\n\n\n lookup = defaultdict(int)\n\n letters = "QWER"\n\n c = Counter(s)\n\n for l in letters:\n res = c[l] - M\n if res > 0:\n lookup[l] = res\n\n \n ... | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** othe... | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
Python Medium | replace-the-substring-for-balanced-string | 0 | 1 | ```\nclass Solution:\n def balancedString(self, s: str) -> int:\n M = len(s) // 4\n\n\n lookup = defaultdict(int)\n\n letters = "QWER"\n\n c = Counter(s)\n\n for l in letters:\n res = c[l] - M\n if res > 0:\n lookup[l] = res\n\n \n ... | 0 | Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the ma... | Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough. |
DP and Recursion in python | maximum-profit-in-job-scheduling | 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)$$ --... | 8 | We have `n` jobs, where every job is scheduled to be done from `startTime[i]` to `endTime[i]`, obtaining a profit of `profit[i]`.
You're given the `startTime`, `endTime` and `profit` arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.
If you choose... | null |
DP and Recursion in python | maximum-profit-in-job-scheduling | 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)$$ --... | 8 | Design an algorithm that accepts a stream of integers and retrieves the product of the last `k` integers of the stream.
Implement the `ProductOfNumbers` class:
* `ProductOfNumbers()` Initializes the object with an empty stream.
* `void add(int num)` Appends the integer `num` to the stream.
* `int getProduct(int... | Think on DP. Sort the elements by starting time, then define the dp[i] as the maximum profit taking elements from the suffix starting at i. Use binarySearch (lower_bound/upper_bound on C++) to get the next index for the DP transition. |
[greedy] just filtering (the easiest funny solution w/o BS, etc.) | maximum-profit-in-job-scheduling | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust filter the options instead of using binary search and other complicated things.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nChoose the best option up to the current point in time. It looks like greedy, doesn... | 1 | We have `n` jobs, where every job is scheduled to be done from `startTime[i]` to `endTime[i]`, obtaining a profit of `profit[i]`.
You're given the `startTime`, `endTime` and `profit` arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.
If you choose... | null |
[greedy] just filtering (the easiest funny solution w/o BS, etc.) | maximum-profit-in-job-scheduling | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust filter the options instead of using binary search and other complicated things.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nChoose the best option up to the current point in time. It looks like greedy, doesn... | 1 | Design an algorithm that accepts a stream of integers and retrieves the product of the last `k` integers of the stream.
Implement the `ProductOfNumbers` class:
* `ProductOfNumbers()` Initializes the object with an empty stream.
* `void add(int num)` Appends the integer `num` to the stream.
* `int getProduct(int... | Think on DP. Sort the elements by starting time, then define the dp[i] as the maximum profit taking elements from the suffix starting at i. Use binarySearch (lower_bound/upper_bound on C++) to get the next index for the DP transition. |
Python 3 -> 91.68% faster. O(n) time | find-positive-integer-solution-for-a-given-equation | 0 | 1 | **Suggestions to make it better are always welcomed.**\n\nWe are working on 2 variables, x & y. Let\'s use 2 pointer approach.\n\n```\ndef findSolution(self, customfunction: \'CustomFunction\', z: int) -> List[List[int]]:\n\tx, y = 1, z\n\tpairs = []\n\t\n\twhile x<=z and y>0:\n\t\tcf = customfunction.f(x,y)\n\t\tif cf... | 30 | Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
* `f(x, y... | null |
Python 3 -> 91.68% faster. O(n) time | find-positive-integer-solution-for-a-given-equation | 0 | 1 | **Suggestions to make it better are always welcomed.**\n\nWe are working on 2 variables, x & y. Let\'s use 2 pointer approach.\n\n```\ndef findSolution(self, customfunction: \'CustomFunction\', z: int) -> List[List[int]]:\n\tx, y = 1, z\n\tpairs = []\n\t\n\twhile x<=z and y>0:\n\t\tcf = customfunction.f(x,y)\n\t\tif cf... | 30 | 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. |
Two Solutions in Python 3 (beats 100%) | find-positive-integer-solution-for-a-given-equation | 0 | 1 | _Without Binary Search:_ (beats 100%)\n```\nclass Solution:\n def findSolution(self, C: \'CustomFunction\', z: int) -> List[List[int]]:\n A, Y = [], z+1 \n for x in range(1,z+1):\n if C.f(x,1) > z: return A\n for y in range(Y,0,-1):\n if C.f(x,y) == z:\n ... | 9 | Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
* `f(x, y... | null |
Two Solutions in Python 3 (beats 100%) | find-positive-integer-solution-for-a-given-equation | 0 | 1 | _Without Binary Search:_ (beats 100%)\n```\nclass Solution:\n def findSolution(self, C: \'CustomFunction\', z: int) -> List[List[int]]:\n A, Y = [], z+1 \n for x in range(1,z+1):\n if C.f(x,1) > z: return A\n for y in range(Y,0,-1):\n if C.f(x,y) == z:\n ... | 9 | 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. |
Python3 | Why am I getting TLE Even though I used Binary Search to Deduce Search Space for Y? | find-positive-integer-solution-for-a-given-equation | 0 | 1 | ```\n"""\n This is the custom function interface.\n You should not implement it, or speculate about its implementation\n class CustomFunction:\n # Returns f(x, y) for any given positive integers x and y.\n # Note that f(x, y) is increasing with respect to both x and y.\n # i.e. f(x, y) < f(x + 1... | 0 | Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
* `f(x, y... | null |
Python3 | Why am I getting TLE Even though I used Binary Search to Deduce Search Space for Y? | find-positive-integer-solution-for-a-given-equation | 0 | 1 | ```\n"""\n This is the custom function interface.\n You should not implement it, or speculate about its implementation\n class CustomFunction:\n # Returns f(x, y) for any given positive integers x and y.\n # Note that f(x, y) is increasing with respect to both x and y.\n # i.e. f(x, y) < f(x + 1... | 0 | 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. |
[Python3] Good enough | find-positive-integer-solution-for-a-given-equation | 0 | 1 | ``` Python3 []\n"""\n This is the custom function interface.\n You should not implement it, or speculate about its implementation\n class CustomFunction:\n # Returns f(x, y) for any given positive integers x and y.\n # Note that f(x, y) is increasing with respect to both x and y.\n # i.e. f(x, y... | 0 | Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
* `f(x, y... | null |
[Python3] Good enough | find-positive-integer-solution-for-a-given-equation | 0 | 1 | ``` Python3 []\n"""\n This is the custom function interface.\n You should not implement it, or speculate about its implementation\n class CustomFunction:\n # Returns f(x, y) for any given positive integers x and y.\n # Note that f(x, y) is increasing with respect to both x and y.\n # i.e. f(x, y... | 0 | 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. |
Smart brute force || Faster than 80% | find-positive-integer-solution-for-a-given-equation | 0 | 1 | # Intuition\nSimply do a linear serach and as we know the function is monotonically increasing if f(x, 1) is greater than z then any value after that would bre greater hence we can simply break\nalso if f(x, y) is greater than > z then f(x, y+1) will be definitely greater hence we can break out of the inner loop\n\n# C... | 0 | Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
* `f(x, y... | null |
Smart brute force || Faster than 80% | find-positive-integer-solution-for-a-given-equation | 0 | 1 | # Intuition\nSimply do a linear serach and as we know the function is monotonically increasing if f(x, 1) is greater than z then any value after that would bre greater hence we can simply break\nalso if f(x, y) is greater than > z then f(x, y+1) will be definitely greater hence we can break out of the inner loop\n\n# C... | 0 | 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. |
Find positive integer solution for a given equation | find-positive-integer-solution-for-a-given-equation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
* `f(x, y... | null |
Find positive integer solution for a given equation | find-positive-integer-solution-for-a-given-equation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given a 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: A Bit of Clever Pattern Recognition | circular-permutation-in-binary-representation | 0 | 1 | # Intuition\r\n\r\nThis is a kind of tricky problem to work out if you try to start with dynamic programming.\r\n\r\nSo instead I tackled it by finding a pattern. First we note that if we can find a pattern starting with 0, then we can do a circular shift of the array to get the final answer.\r\n* `n=1: [0, 1]`\r\n* `n... | 0 | Given 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that :
* `p[0] = start`
* `p[i]` and `p[i+1]` differ by only one bit in their binary representation.
* `p[0]` and `p[2^n -1]` must also differ by only one bit in their binary representation.
**Example 1:*... | Create a hashmap from letter to position on the board. Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board. |
Python 3: A Bit of Clever Pattern Recognition | circular-permutation-in-binary-representation | 0 | 1 | # Intuition\r\n\r\nThis is a kind of tricky problem to work out if you try to start with dynamic programming.\r\n\r\nSo instead I tackled it by finding a pattern. First we note that if we can find a pattern starting with 0, then we can do a circular shift of the array to get the final answer.\r\n* `n=1: [0, 1]`\r\n* `n... | 0 | 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 | circular-permutation-in-binary-representation | 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 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that :
* `p[0] = start`
* `p[i]` and `p[i+1]` differ by only one bit in their binary representation.
* `p[0]` and `p[2^n -1]` must also differ by only one bit in their binary representation.
**Example 1:*... | Create a hashmap from letter to position on the board. Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board. |
Python | circular-permutation-in-binary-representation | 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 `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 Gray's code) | circular-permutation-in-binary-representation | 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 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that :
* `p[0] = start`
* `p[i]` and `p[i+1]` differ by only one bit in their binary representation.
* `p[0]` and `p[2^n -1]` must also differ by only one bit in their binary representation.
**Example 1:*... | Create a hashmap from letter to position on the board. Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board. |
Python (Simple Gray's code) | circular-permutation-in-binary-representation | 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 `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 DFS approach | circular-permutation-in-binary-representation | 0 | 1 | # Code\n```\nclass Solution:\n def circularPermutation(self, n: int, start: int) -> List[int]:\n N = 1<<n\n vis = [False]*N\n def dfs(u,st):\n vis[u] = True\n st.append(u)\n for i in range(n):\n v = u^(1<<i)\n if(not vis[v]): dfs(v,... | 0 | Given 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that :
* `p[0] = start`
* `p[i]` and `p[i+1]` differ by only one bit in their binary representation.
* `p[0]` and `p[2^n -1]` must also differ by only one bit in their binary representation.
**Example 1:*... | Create a hashmap from letter to position on the board. Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board. |
[Python] Simple DFS approach | circular-permutation-in-binary-representation | 0 | 1 | # Code\n```\nclass Solution:\n def circularPermutation(self, n: int, start: int) -> List[int]:\n N = 1<<n\n vis = [False]*N\n def dfs(u,st):\n vis[u] = True\n st.append(u)\n for i in range(n):\n v = u^(1<<i)\n if(not vis[v]): dfs(v,... | 0 | 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 solution beats 98%. W/ explanation | circular-permutation-in-binary-representation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is to find all the possible binary permutations of a given length n, and starting from a given starting number. The circular permutation means that the permutations will be arranged in a circular manner, so that the last eleme... | 0 | Given 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that :
* `p[0] = start`
* `p[i]` and `p[i+1]` differ by only one bit in their binary representation.
* `p[0]` and `p[2^n -1]` must also differ by only one bit in their binary representation.
**Example 1:*... | Create a hashmap from letter to position on the board. Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board. |
Python solution beats 98%. W/ explanation | circular-permutation-in-binary-representation | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is to find all the possible binary permutations of a given length n, and starting from a given starting number. The circular permutation means that the permutations will be arranged in a circular manner, so that the last eleme... | 0 | 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 Elegant & Short | DP | maximum-length-of-a-concatenated-string-with-unique-characters | 0 | 1 | ```\nclass Solution:\n """\n Time: O(n^2)\n Memory: O(n^2)\n """\n\n def maxLength(self, sequences: List[str]) -> int:\n dp = [set()]\n\n for seq in sequences:\n chars = set(seq)\n\n if len(chars) < len(seq):\n continue\n\n dp.extend(chars |... | 13 | You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**.
Return _the **maximum** possible length_ of `s`.
A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing ... | For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1). |
Python Elegant & Short | DP | maximum-length-of-a-concatenated-string-with-unique-characters | 0 | 1 | ```\nclass Solution:\n """\n Time: O(n^2)\n Memory: O(n^2)\n """\n\n def maxLength(self, sequences: List[str]) -> int:\n dp = [set()]\n\n for seq in sequences:\n chars = set(seq)\n\n if len(chars) < len(seq):\n continue\n\n dp.extend(chars |... | 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. |
[Python3] Easy Understanding -- Bitmask + DFS | maximum-length-of-a-concatenated-string-with-unique-characters | 0 | 1 | ```\nclass Solution:\n def maxLength(self, arr: List[str]) -> int:\n arr_masks = []\n for s in arr:\n mask = 0\n uniq = True\n for c in s:\n shift = ord(c) - ord(\'a\')\n if (1 << shift) & mask == 0:\n mask |= (1 << shift... | 1 | You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**.
Return _the **maximum** possible length_ of `s`.
A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing ... | For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1). |
[Python3] Easy Understanding -- Bitmask + DFS | maximum-length-of-a-concatenated-string-with-unique-characters | 0 | 1 | ```\nclass Solution:\n def maxLength(self, arr: List[str]) -> int:\n arr_masks = []\n for s in arr:\n mask = 0\n uniq = True\n for c in s:\n shift = ord(c) - ord(\'a\')\n if (1 << shift) & mask == 0:\n mask |= (1 << shift... | 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 3: DFS + Backtracking: Skyline, Fill the Bottom-Left Cell(s) First | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Intuition\n\nThe hardest part about this question is figuring out how you can efficiently try all of the combinations.\n\nThe second example in particular shows the difficulty - how do you make sure you try the size-1 square in the middle??\n\n## Strategy: "You Have to Start Somewhere"\n\nWhen in doubt, in these kind... | 0 | Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_.
**Example 1:**
**Input:** n = 2, m = 3
**Output:** 3
**Explanation:** `3` squares are necessary to cover the rectangle.
`2` (squares of `1x1`)
`1` (square of `2x2`)
**Example 2:**
**Input:** n = 5, m =... | Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m. |
Python 3: DFS + Backtracking: Skyline, Fill the Bottom-Left Cell(s) First | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Intuition\n\nThe hardest part about this question is figuring out how you can efficiently try all of the combinations.\n\nThe second example in particular shows the difficulty - how do you make sure you try the size-1 square in the middle??\n\n## Strategy: "You Have to Start Somewhere"\n\nWhen in doubt, in these kind... | 0 | 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 skyline | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Approach\nKeep track of the right view skyline of the rectangle that we have filled with squares, which is represented by a heap of right sides of squares. Then iteratively take the leftmost rooftop and place a new square on it.\n\n# Code\n```\nimport heapq\n\nclass Solution:\n def tilingRectangle(self, n: int, m:... | 0 | Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_.
**Example 1:**
**Input:** n = 2, m = 3
**Output:** 3
**Explanation:** `3` squares are necessary to cover the rectangle.
`2` (squares of `1x1`)
`1` (square of `2x2`)
**Example 2:**
**Input:** n = 5, m =... | Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m. |
Python skyline | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Approach\nKeep track of the right view skyline of the rectangle that we have filled with squares, which is represented by a heap of right sides of squares. Then iteratively take the leftmost rooftop and place a new square on it.\n\n# Code\n```\nimport heapq\n\nclass Solution:\n def tilingRectangle(self, n: int, m:... | 0 | 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). |
Fast Python Solution | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Code\n```\nclass Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n if n == m: return 1\n depth = [0]*m\n \n def fn(x): \n """Explore tiling rectangle area via backtracking."""\n nonlocal ans \n if x < ans: \n if min(depth) ==... | 0 | Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_.
**Example 1:**
**Input:** n = 2, m = 3
**Output:** 3
**Explanation:** `3` squares are necessary to cover the rectangle.
`2` (squares of `1x1`)
`1` (square of `2x2`)
**Example 2:**
**Input:** n = 5, m =... | Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m. |
Fast Python Solution | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Code\n```\nclass Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n if n == m: return 1\n depth = [0]*m\n \n def fn(x): \n """Explore tiling rectangle area via backtracking."""\n nonlocal ans \n if x < ans: \n if min(depth) ==... | 0 | 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 backtrack solution | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrom hint, we can try backtrack, use a 2D array as board to record where already put rectangle on it, and search for empty space for new rectangle. but here we need some important optimization, otherwise it will go TLE.\n\n# Approach\n<!-... | 0 | Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_.
**Example 1:**
**Input:** n = 2, m = 3
**Output:** 3
**Explanation:** `3` squares are necessary to cover the rectangle.
`2` (squares of `1x1`)
`1` (square of `2x2`)
**Example 2:**
**Input:** n = 5, m =... | Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m. |
Python backtrack solution | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrom hint, we can try backtrack, use a 2D array as board to record where already put rectangle on it, and search for empty space for new rectangle. but here we need some important optimization, otherwise it will go TLE.\n\n# Approach\n<!-... | 0 | 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). |
Bottom Up Approach utilizing Transpose and minimal siding speed up | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTiling approach can be solved in limited looping with memoization. Seems brutish, but this is actually one of the better ways to solve this it turns out (cool links on tessalation on wiki for this). Two edge cases to consider, namely that... | 0 | Given a rectangle of size `n` x `m`, return _the minimum number of integer-sided squares that tile the rectangle_.
**Example 1:**
**Input:** n = 2, m = 3
**Output:** 3
**Explanation:** `3` squares are necessary to cover the rectangle.
`2` (squares of `1x1`)
`1` (square of `2x2`)
**Example 2:**
**Input:** n = 5, m =... | Use dynamic programming: the states are (i, m) for the answer of piles[i:] and that given m. |
Bottom Up Approach utilizing Transpose and minimal siding speed up | tiling-a-rectangle-with-the-fewest-squares | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTiling approach can be solved in limited looping with memoization. Seems brutish, but this is actually one of the better ways to solve this it turns out (cool links on tessalation on wiki for this). Two edge cases to consider, namely that... | 0 | 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). |
Simply Simple Python Solution - with detailed explanation | minimum-swaps-to-make-strings-equal | 0 | 1 | In this problem, we just need to find the count of different characters in both strings. When I use "x_y" i.e. I have x in s1 at index i and y in s2 at same index i. Similary "y_x" means I have y in s1 at index j and x in s2 at same index j. \n\n#### Example 1:\ns1 = "xx"\ns2 = "yy"\n\nif we iterate through both string... | 200 | You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`.
Return the minimum number of swaps required ... | Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors. |
85% O(n) TC and 81% O(1) SC easy python solution | minimum-swaps-to-make-strings-equal | 0 | 1 | ```\ndef minimumSwap(self, s1: str, s2: str) -> int:\n\txy = yx = 0\n\tfor i in range(len(s1)):\n\t\tif(s1[i] == "x" and s2[i] == "y"):\n\t\t\txy += 1\n\t\tif(s2[i] == "x" and s1[i] == "y"):\n\t\t\tyx += 1\n\tif(xy%2 ^ yx%2):\n\t\treturn -1\n\tans = xy//2 + yx//2 + (xy%2) * 2\n\treturn ans\n``` | 1 | You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`.
Return the minimum number of swaps required ... | Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors. |
python 3 || simple greedy solution || O(n)/O(1) | minimum-swaps-to-make-strings-equal | 0 | 1 | ```\nclass Solution:\n def minimumSwap(self, s1: str, s2: str) -> int:\n xy = yx = 0\n for c1, c2 in zip(s1, s2):\n if c1 == \'x\' and c2 == \'y\':\n xy += 1\n elif c1 == \'y\' and c2 == \'x\':\n yx += 1\n \n if (xy + yx) % 2:\n ... | 1 | You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`.
Return the minimum number of swaps required ... | Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors. |
Python 3: Count Pairs | minimum-swaps-to-make-strings-equal | 0 | 1 | # Intuition\n\nI took a long time to fix this, probably would have failed an interview question if I only had 20 minutes with no hints :(\n\nAnyway, after some failed attempts I first realized tha the rules of swapping mean we don\'t care about where the indices `i` and `j` are, just that they\'re in different strings.... | 0 | You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`.
Return the minimum number of swaps required ... | Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors. |
✅counting solution || python | minimum-swaps-to-make-strings-equal | 0 | 1 | \n# Code\n```\nclass Solution:\n def minimumSwap(self, s1: str, s2: str) -> int:\n cx1=0\n cx2=0\n for i in s1:\n if(i==\'x\'):cx1+=1\n for i in s2:\n if(i==\'x\'):cx2+=1\n if((cx1+cx2)%2!=0):return -1\n cx1=0\n cx2=0\n for i in range(len(... | 0 | You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`.
Return the minimum number of swaps required ... | Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors. |
Easy Solution | count-number-of-nice-subarrays | 0 | 1 | # Code\n```\nclass Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n ans = 0\n helper = [-1] + [i for i, el in enumerate(nums) if el % 2] + [len(nums)]\n\n for i in range(1, len(helper) - k):\n ans += (helper[i] - helper[i - 1]) * (helper[i + k] - helper[i + k... | 2 | Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it.
Return _the number of **nice** sub-arrays_.
**Example 1:**
**Input:** nums = \[1,1,2,1,1\], k = 3
**Output:** 2
**Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] an... | The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x? |
Easy Solution | count-number-of-nice-subarrays | 0 | 1 | # Code\n```\nclass Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n ans = 0\n helper = [-1] + [i for i, el in enumerate(nums) if el % 2] + [len(nums)]\n\n for i in range(1, len(helper) - k):\n ans += (helper[i] - helper[i - 1]) * (helper[i + k] - helper[i + k... | 2 | You are given a string `s`. Reorder the string using the following algorithm:
1. Pick the **smallest** character from `s` and **append** it to the result.
2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it.
3. Repeat step 2 until you cannot ... | After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.