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 | Math Puzzle | O(n) | sum-game | 0 | 1 | # Code\n```\nclass Solution:\n def sumGame(self, num: str) -> bool:\n n = len(num)\n qcnt1 = s1 = 0\n for i in range(n//2):\n if num[i] == \'?\':\n qcnt1 += 1\n else:\n s1 += int(num[i])\n qcnt2 = s2 = 0\n for i in range(n//2, n):... | 0 | Alice and Bob take turns playing a game, with **Alice** **starting first**.
You are given a string `num` of **even length** consisting of digits and `'?'` characters. On each turn, a player will do the following if there is still at least one `'?'` in `num`:
1. Choose an index `i` where `num[i] == '?'`.
2. Replace ... | It is fast enough to check all possible subarrays The end of each ascending subarray will be the start of the next |
Easy solution Python (time performance >90-100%) | minimum-cost-to-reach-destination-in-time | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis one is particularly tricky since the solution is supersimple but there is a small tip that is needed to avoid MLE and TLE.\n\nThe basic idea is using a priority queue with aggregated cost as key. With this approach you are able to pa... | 0 | There is a country of `n` cities numbered from `0` to `n - 1` where **all the cities are connected** by bi-directional roads. The roads are represented as a 2D integer array `edges` where `edges[i] = [xi, yi, timei]` denotes a road between cities `xi` and `yi` that takes `timei` minutes to travel. There may be multiple... | Store the backlog buy and sell orders in two heaps, the buy orders in a max heap by price and the sell orders in a min heap by price. Store the orders in batches and update the fields according to new incoming orders. Each batch should only take 1 "slot" in the heap. |
Easy Python Solution Using heap | 99% Faster | | minimum-cost-to-reach-destination-in-time | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | There is a country of `n` cities numbered from `0` to `n - 1` where **all the cities are connected** by bi-directional roads. The roads are represented as a 2D integer array `edges` where `edges[i] = [xi, yi, timei]` denotes a road between cities `xi` and `yi` that takes `timei` minutes to travel. There may be multiple... | Store the backlog buy and sell orders in two heaps, the buy orders in a max heap by price and the sell orders in a min heap by price. Store the orders in batches and update the fields according to new incoming orders. Each batch should only take 1 "slot" in the heap. |
Edge Pruning and Priority Queue BFS | Commented and Explained | 100% Time wo comments | minimum-cost-to-reach-destination-in-time | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBased on the problem description our initial set of edges is not suitable for a standard approach (multiple edges of different times but same cost between nodes). This lets us know we will need a pruning approach. The second part of the p... | 0 | There is a country of `n` cities numbered from `0` to `n - 1` where **all the cities are connected** by bi-directional roads. The roads are represented as a 2D integer array `edges` where `edges[i] = [xi, yi, timei]` denotes a road between cities `xi` and `yi` that takes `timei` minutes to travel. There may be multiple... | Store the backlog buy and sell orders in two heaps, the buy orders in a max heap by price and the sell orders in a min heap by price. Store the orders in batches and update the fields according to new incoming orders. Each batch should only take 1 "slot" in the heap. |
Python straight forward DP, easy to understand, but slow and memory consuming | minimum-cost-to-reach-destination-in-time | 0 | 1 | <!-- # Intuition -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n<!-- # Approach -->\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(t \\cdot V \\cdot E)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(V \\c... | 0 | There is a country of `n` cities numbered from `0` to `n - 1` where **all the cities are connected** by bi-directional roads. The roads are represented as a 2D integer array `edges` where `edges[i] = [xi, yi, timei]` denotes a road between cities `xi` and `yi` that takes `timei` minutes to travel. There may be multiple... | Store the backlog buy and sell orders in two heaps, the buy orders in a max heap by price and the sell orders in a min heap by price. Store the orders in batches and update the fields according to new incoming orders. Each batch should only take 1 "slot" in the heap. |
Python3 and C++ solutions | concatenation-of-array | 0 | 1 | # Solution in C++\n```\nclass Solution {\npublic:\n \n vector<int> getConcatenation(vector<int>& nums) {\n vector<int> ans;\n ans = nums;\n for (int i = 0; i < nums.size(); i++) {\n ans.push_back(nums[i]);\n }\n return ans;\n }\n};\n```\n# Solution in Python3\n```\... | 2 | Given an integer array `nums` of length `n`, you want to create an array `ans` of length `2n` where `ans[i] == nums[i]` and `ans[i + n] == nums[i]` for `0 <= i < n` (**0-indexed**).
Specifically, `ans` is the **concatenation** of two `nums` arrays.
Return _the array_ `ans`.
**Example 1:**
**Input:** nums = \[1,2,1\... | What if the problem was instead determining if you could generate a valid array with nums[index] == target? To generate the array, set nums[index] to target, nums[index-i] to target-i, and nums[index+i] to target-i. Then, this will give the minimum possible sum, so check if the sum is less than or equal to maxSum. n is... |
🥇 C++ | PYTHON | JAVA | O(N) || EXPLAINED || ; ] | unique-length-3-palindromic-subsequences | 1 | 1 | **UPVOTE IF HELPFuuL**\n\n# Intuition\nWe need to find the number of unique of ```PalindromicSubsequence```, hence repitition is not a case to be done here.\n\n# Approach\nFor every char ```$``` in ```[a,b,c...y,z]``` , a palindrome of type ```"$ @ $"``` will exist if there are atleast 2 occurances of ```"$"```.\n\nHen... | 30 | Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**.
A **palindrome** is a string that reads the same forwards and backwards.
A **subsequence** ... | If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x. |
🚀 Iterative Solution || Explained Intuition 🚀 | unique-length-3-palindromic-subsequences | 1 | 1 | # Problem Description\n\nGiven a string `s`, calculates the count of **unique** palindromes of length **three** that can be formed as **subsequences** within `s`. \n\nA **palindrome** is a string that reads the **same** forward and backward. In this context, a **subsequence** of a string is a new string formed by **del... | 144 | Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**.
A **palindrome** is a string that reads the same forwards and backwards.
A **subsequence** ... | If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x. |
Binary search on character positions - beats 100% | unique-length-3-palindromic-subsequences | 0 | 1 | # Intuition\nFor each letter check if there is another letter in between its min and max positions\n\n# Approach\nStore positions for each character\nLoop over combinations of two characters. Take min and max positions from one of them and check if there is a position in between them for the second char using binary se... | 5 | Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**.
A **palindrome** is a string that reads the same forwards and backwards.
A **subsequence** ... | If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x. |
[Python3] DP 5 Cases | painting-a-grid-with-three-different-colors | 0 | 1 | **DP 5 Cases**\n\n**Inuition**\n\nThere are only 5 cases to handle (`1 <= m <= 5`). Since `m` is small the recurrence relations per `m` can be discovered and returned.\n\nWith `m` fixed, for each time we increase `n` think in terms of possible `1*m` blocks that can be added to all existing `(n - 1)*m` blocks. \n\n**Cas... | 2 | You are given two integers `m` and `n`. Consider an `m x n` grid where each cell is initially white. You can paint each cell **red**, **green**, or **blue**. All cells **must** be painted.
Return _the number of ways to color the grid with **no two adjacent cells having the same color**_. Since the answer can be very l... | The grid is at a maximum 500 x 500, so it is clever to assume that the robot's initial cell is grid[501][501] Run a DFS from the robot's position to make sure that you can reach the target, otherwise you should return -1. Now that you are sure you can reach the target, run BFS to find the shortest path. |
python DP top down | painting-a-grid-with-three-different-colors | 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 two integers `m` and `n`. Consider an `m x n` grid where each cell is initially white. You can paint each cell **red**, **green**, or **blue**. All cells **must** be painted.
Return _the number of ways to color the grid with **no two adjacent cells having the same color**_. Since the answer can be very l... | The grid is at a maximum 500 x 500, so it is clever to assume that the robot's initial cell is grid[501][501] Run a DFS from the robot's position to make sure that you can reach the target, otherwise you should return -1. Now that you are sure you can reach the target, run BFS to find the shortest path. |
No bitmask | painting-a-grid-with-three-different-colors | 0 | 1 | \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nb=[]\ndef gen(s,n):\n global b\n if len(s)==n:\n fl=False\n for i in range(1,n):\n fl|=s[i]==s[i-1]\n if not fl:\n b.append(s)\n return\n gen(s+"0",n)\n gen(s+"1",n)\n gen(s+"2",n)\n... | 0 | You are given two integers `m` and `n`. Consider an `m x n` grid where each cell is initially white. You can paint each cell **red**, **green**, or **blue**. All cells **must** be painted.
Return _the number of ways to color the grid with **no two adjacent cells having the same color**_. Since the answer can be very l... | The grid is at a maximum 500 x 500, so it is clever to assume that the robot's initial cell is grid[501][501] Run a DFS from the robot's position to make sure that you can reach the target, otherwise you should return -1. Now that you are sure you can reach the target, run BFS to find the shortest path. |
Python Solution | painting-a-grid-with-three-different-colors | 0 | 1 | \n\n# Approach\nHere\'s a step-by-step explanation of the solution:\n\n1. Generate all valid rows:\nThe generate_valid_rows function generates all valid rows of length m, with no... | 0 | You are given two integers `m` and `n`. Consider an `m x n` grid where each cell is initially white. You can paint each cell **red**, **green**, or **blue**. All cells **must** be painted.
Return _the number of ways to color the grid with **no two adjacent cells having the same color**_. Since the answer can be very l... | The grid is at a maximum 500 x 500, so it is clever to assume that the robot's initial cell is grid[501][501] Run a DFS from the robot's position to make sure that you can reach the target, otherwise you should return -1. Now that you are sure you can reach the target, run BFS to find the shortest path. |
[Python 3] Bitmask DP | painting-a-grid-with-three-different-colors | 0 | 1 | # Intuition\nsince m is very small so it seems sensible to use Bitmask DP here\n\n# Approach\nwe use first 5 bits for red, next 5 for blue and next 5 bits for green\nand continously check for each position if we can use a specific color.\n\n# Time Compexity:\nO(n\\*m\\*2^(2\\*m))\n\n# Code\n```\nclass Solution:\n de... | 0 | You are given two integers `m` and `n`. Consider an `m x n` grid where each cell is initially white. You can paint each cell **red**, **green**, or **blue**. All cells **must** be painted.
Return _the number of ways to color the grid with **no two adjacent cells having the same color**_. Since the answer can be very l... | The grid is at a maximum 500 x 500, so it is clever to assume that the robot's initial cell is grid[501][501] Run a DFS from the robot's position to make sure that you can reach the target, otherwise you should return -1. Now that you are sure you can reach the target, run BFS to find the shortest path. |
Python Solution beats 100% Time | merge-bsts-to-create-single-bst | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You are given `n` **BST (binary search tree) root nodes** for `n` separate BSTs stored in an array `trees` (**0-indexed**). Each BST in `trees` has **at most 3 nodes**, and no two roots have the same value. In one operation, you can:
* Select two **distinct** indices `i` and `j` such that the value stored at one of ... | null |
Map Tree Conditions | Commented and Explained | merge-bsts-to-create-single-bst | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA binary search tree that is valid is a graph of contracts of node relations. As such, we can use graphs and sets of tree node relations and utilize them to determine validity. Validity needs to agree on a node level, and as a whole tree,... | 0 | You are given `n` **BST (binary search tree) root nodes** for `n` separate BSTs stored in an array `trees` (**0-indexed**). Each BST in `trees` has **at most 3 nodes**, and no two roots have the same value. In one operation, you can:
* Select two **distinct** indices `i` and `j` such that the value stored at one of ... | null |
Python3 | merge-bsts-to-create-single-bst | 0 | 1 | ```\nfrom typing import List, Optional\n\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def __init__(self):\n self.blacklist = set()\n self.value2node = {}\n self.opera... | 0 | You are given `n` **BST (binary search tree) root nodes** for `n` separate BSTs stored in an array `trees` (**0-indexed**). Each BST in `trees` has **at most 3 nodes**, and no two roots have the same value. In one operation, you can:
* Select two **distinct** indices `i` and `j` such that the value stored at one of ... | null |
Easy to understand Python3 solution | maximum-number-of-words-you-can-type | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.
Given a string `text` of words separated by a single space (no leading or trailing spaces) and a string `brokenLetters` of all **distinct** letter keys that are broken, return _the **number of words** i... | It is safe to assume the number of operations isn't more than n The number is small enough to apply a brute force solution. |
🔥[Python 3] Simple Set intersection 2 lines, beats 89% 🥷🏼 | maximum-number-of-words-you-can-type | 0 | 1 | ```python3 []\nclass Solution:\n def canBeTypedWords(self, text: str, brokenLetters: str) -> int:\n broken = set(brokenLetters)\n return sum(not set(w) & broken for w in text.split())\n```\n```python3 []\nclass Solution:\n def canBeTypedWords(self, text: str, brokenLetters: str) -> int:\n res... | 4 | There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.
Given a string `text` of words separated by a single space (no leading or trailing spaces) and a string `brokenLetters` of all **distinct** letter keys that are broken, return _the **number of words** i... | It is safe to assume the number of operations isn't more than n The number is small enough to apply a brute force solution. |
O(n) solution with set(explanation) python faster than others | maximum-number-of-words-you-can-type | 0 | 1 | \n```\ncounter = 0\nfor i in text.split():\n #{\'a\',\'b\'}.intersection(\'a\') is equal to {\'a\'} \n #according to this if this expression returned empty set then we\'ll increment\n if set(brokenLetters).intersection(set(i)) == set():\n counter+=1\nreturn counter\n``` | 2 | There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.
Given a string `text` of words separated by a single space (no leading or trailing spaces) and a string `brokenLetters` of all **distinct** letter keys that are broken, return _the **number of words** i... | It is safe to assume the number of operations isn't more than n The number is small enough to apply a brute force solution. |
Easy, Fast Python Solutions (2 Approaches - 28ms, 32ms; Faster than 93%) | maximum-number-of-words-you-can-type | 0 | 1 | # Easy, Fast Python Solutions (2 Approaches - 28ms, 32ms; Faster than 93%)\n## Approach 1 - Using Sets\n**Runtime: 28 ms, faster than 93% of Python3 online submissions for Maximum Number of Words You Can Type.**\n**Memory Usage: 14.4 MB**\n```\nclass Solution:\n def canBeTypedWords(self, text: str, brokenLetters: st... | 13 | There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.
Given a string `text` of words separated by a single space (no leading or trailing spaces) and a string `brokenLetters` of all **distinct** letter keys that are broken, return _the **number of words** i... | It is safe to assume the number of operations isn't more than n The number is small enough to apply a brute force solution. |
p3 1 line | maximum-number-of-words-you-can-type | 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 | There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.
Given a string `text` of words separated by a single space (no leading or trailing spaces) and a string `brokenLetters` of all **distinct** letter keys that are broken, return _the **number of words** i... | It is safe to assume the number of operations isn't more than n The number is small enough to apply a brute force solution. |
python3 | maximum-number-of-words-you-can-type | 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- O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(1)\n<!-- Add your space complexity here, ... | 3 | There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.
Given a string `text` of words separated by a single space (no leading or trailing spaces) and a string `brokenLetters` of all **distinct** letter keys that are broken, return _the **number of words** i... | It is safe to assume the number of operations isn't more than n The number is small enough to apply a brute force solution. |
Python 1-Liner!! | maximum-number-of-words-you-can-type | 0 | 1 | ```py\nclass Solution:\n def canBeTypedWords(self, text: str, brokenLetters: str) -> int:\n return len([i for i in text.split(\' \') if len(set(i).intersection(brokenLetters))==0])\n | 1 | There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.
Given a string `text` of words separated by a single space (no leading or trailing spaces) and a string `brokenLetters` of all **distinct** letter keys that are broken, return _the **number of words** i... | It is safe to assume the number of operations isn't more than n The number is small enough to apply a brute force solution. |
Divide gaps by dist | add-minimum-number-of-rungs | 1 | 1 | The only trick here is to use division, as the gap between two rungs could be large. We will get TLE if we add rungs one-by-one.\n\n**Java**\n```java\npublic int addRungs(int[] rungs, int dist) {\n int res = (rungs[0] - 1) / dist;\n for (int i = 1; i < rungs.length; ++i)\n res += (rungs[i] - rungs[i - 1] -... | 39 | You are given a **strictly increasing** integer array `rungs` that represents the **height** of rungs on a ladder. You are currently on the **floor** at height `0`, and you want to reach the last rung.
You are also given an integer `dist`. You can only climb to the next highest rung if the distance between where you a... | The number of nice divisors is equal to the product of the count of each prime factor. Then the problem is reduced to: given n, find a sequence of numbers whose sum equals n and whose product is maximized. This sequence can have no numbers that are larger than 4. Proof: if it contains a number x that is larger than 4, ... |
Simple python code | add-minimum-number-of-rungs | 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 **strictly increasing** integer array `rungs` that represents the **height** of rungs on a ladder. You are currently on the **floor** at height `0`, and you want to reach the last rung.
You are also given an integer `dist`. You can only climb to the next highest rung if the distance between where you a... | The number of nice divisors is equal to the product of the count of each prime factor. Then the problem is reduced to: given n, find a sequence of numbers whose sum equals n and whose product is maximized. This sequence can have no numbers that are larger than 4. Proof: if it contains a number x that is larger than 4, ... |
Simple and clear python3 solution | add-minimum-number-of-rungs | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nclass Solution:\n def addRungs(self, rungs: List[int], dist: int) -> int:\n result = 0\n pr... | 0 | You are given a **strictly increasing** integer array `rungs` that represents the **height** of rungs on a ladder. You are currently on the **floor** at height `0`, and you want to reach the last rung.
You are also given an integer `dist`. You can only climb to the next highest rung if the distance between where you a... | The number of nice divisors is equal to the product of the count of each prime factor. Then the problem is reduced to: given n, find a sequence of numbers whose sum equals n and whose product is maximized. This sequence can have no numbers that are larger than 4. Proof: if it contains a number x that is larger than 4, ... |
Python3, 4 lines only! (yep, a bit tricky ones ;-) ) | add-minimum-number-of-rungs | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def addRungs(self, rungs: List[int], dist: int) -> int:\n rung, result = 0, 0\n for r in rungs:\n rung, result = r, result if r - rung <= dist else result + ((r - rung) // dist + (-1 i... | 0 | You are given a **strictly increasing** integer array `rungs` that represents the **height** of rungs on a ladder. You are currently on the **floor** at height `0`, and you want to reach the last rung.
You are also given an integer `dist`. You can only climb to the next highest rung if the distance between where you a... | The number of nice divisors is equal to the product of the count of each prime factor. Then the problem is reduced to: given n, find a sequence of numbers whose sum equals n and whose product is maximized. This sequence can have no numbers that are larger than 4. Proof: if it contains a number x that is larger than 4, ... |
Python: Dynamic Programming O(mn) Solution | maximum-number-of-points-with-cost | 0 | 1 | \n\n```\nclass Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n m, n = len(points), len(points[0])\n \n dp = points[0]\n \n left = [0] * n ## left side c... | 17 | You are given an `m x n` integer matrix `points` (**0-indexed**). Starting with `0` points, you want to **maximize** the number of points you can get from the matrix.
To gain points, you must pick one cell in **each row**. Picking the cell at coordinates `(r, c)` will **add** `points[r][c]` to your score.
However, yo... | Consider every possible beauty and its first and last index in flowers. Remove all flowers with negative beauties within those indices. |
easy hashmap solution python 3 | maximum-genetic-difference-query | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | There is a rooted tree consisting of `n` nodes numbered `0` to `n - 1`. Each node's number denotes its **unique genetic value** (i.e. the genetic value of node `x` is `x`). The **genetic difference** between two genetic values is defined as the **bitwise-****XOR** of their values. You are given the integer array `paren... | nums[i+1] must be at least equal to nums[i] + 1. Think greedily. You don't have to increase nums[i+1] beyond nums[i]+1. Iterate on i and set nums[i] = max(nums[i-1]+1, nums[i]) . |
Python, recursive before-order calculation | maximum-genetic-difference-query | 0 | 1 | # Intuition\nLet\'s rephrase problem little bit: if we have query `node,val` can answer have bit prefix `mask`? This gives us next ideas\n1. valid `mask` is always some bit prefix of `p^val` for some parent `p` of `node` (including `node`) \n2. To get the answer we can incrementally improve `mask` prefix. \nLet\'s say ... | 0 | There is a rooted tree consisting of `n` nodes numbered `0` to `n - 1`. Each node's number denotes its **unique genetic value** (i.e. the genetic value of node `x` is `x`). The **genetic difference** between two genetic values is defined as the **bitwise-****XOR** of their values. You are given the integer array `paren... | nums[i+1] must be at least equal to nums[i] + 1. Think greedily. You don't have to increase nums[i+1] beyond nums[i]+1. Iterate on i and set nums[i] = max(nums[i-1]+1, nums[i]) . |
O(32 * (nlogn+mlogn)) python (tle), can take realtime queries | maximum-genetic-difference-query | 0 | 1 | # Intuition\nFuck this tle based on constraints this should be fine\n\n# Code\n```\nclass Node:\n def __init__(self):\n self.containedRanges = {0: [], 1: []}\n self.children = defaultdict(Node)\n\nclass Solution:\n def maxGeneticDifference(self, parents: List[int], queries: List[List[int]]) -> List[... | 0 | There is a rooted tree consisting of `n` nodes numbered `0` to `n - 1`. Each node's number denotes its **unique genetic value** (i.e. the genetic value of node `x` is `x`). The **genetic difference** between two genetic values is defined as the **bitwise-****XOR** of their values. You are given the integer array `paren... | nums[i+1] must be at least equal to nums[i] + 1. Think greedily. You don't have to increase nums[i+1] beyond nums[i]+1. Iterate on i and set nums[i] = max(nums[i-1]+1, nums[i]) . |
[Python3] bit trie | maximum-genetic-difference-query | 0 | 1 | \n```\nclass Trie: \n def __init__(self): \n self.root = {}\n \n def insert(self, x): \n node = self.root\n for i in range(18, -1, -1): \n bit = (x >> i) & 1\n node = node.setdefault(bit, {})\n node["mult"] = 1 + node.get("mult", 0)\n node["#"] = x #... | 1 | There is a rooted tree consisting of `n` nodes numbered `0` to `n - 1`. Each node's number denotes its **unique genetic value** (i.e. the genetic value of node `x` is `x`). The **genetic difference** between two genetic values is defined as the **bitwise-****XOR** of their values. You are given the integer array `paren... | nums[i+1] must be at least equal to nums[i] + 1. Think greedily. You don't have to increase nums[i+1] beyond nums[i]+1. Iterate on i and set nums[i] = max(nums[i-1]+1, nums[i]) . |
python solution | check-if-all-characters-have-equal-number-of-occurrences | 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 | Given a string `s`, return `true` _if_ `s` _is a **good** string, or_ `false` _otherwise_.
A string `s` is **good** if **all** the characters that appear in `s` have the **same** number of occurrences (i.e., the same frequency).
**Example 1:**
**Input:** s = "abacbc "
**Output:** true
**Explanation:** The character... | Note that the operations given describe getting the previous permutation of s To solve this problem you need to solve every suffix separately |
Best & Easiest Python Solution | check-if-all-characters-have-equal-number-of-occurrences | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given a string `s`, return `true` _if_ `s` _is a **good** string, or_ `false` _otherwise_.
A string `s` is **good** if **all** the characters that appear in `s` have the **same** number of occurrences (i.e., the same frequency).
**Example 1:**
**Input:** s = "abacbc "
**Output:** true
**Explanation:** The character... | Note that the operations given describe getting the previous permutation of s To solve this problem you need to solve every suffix separately |
One liner solution easy using counter to count no of occurrences and then convert into set | check-if-all-characters-have-equal-number-of-occurrences | 0 | 1 | # Code\n```\nclass Solution:\n def areOccurrencesEqual(self, s: str) -> bool:\n return len(set(Counter(s).values()))==1\n``` | 1 | Given a string `s`, return `true` _if_ `s` _is a **good** string, or_ `false` _otherwise_.
A string `s` is **good** if **all** the characters that appear in `s` have the **same** number of occurrences (i.e., the same frequency).
**Example 1:**
**Input:** s = "abacbc "
**Output:** true
**Explanation:** The character... | Note that the operations given describe getting the previous permutation of s To solve this problem you need to solve every suffix separately |
[Python3] 1-line | check-if-all-characters-have-equal-number-of-occurrences | 0 | 1 | \n```\nclass Solution:\n def areOccurrencesEqual(self, s: str) -> bool:\n return len(set(Counter(s).values())) == 1\n``` | 44 | Given a string `s`, return `true` _if_ `s` _is a **good** string, or_ `false` _otherwise_.
A string `s` is **good** if **all** the characters that appear in `s` have the **same** number of occurrences (i.e., the same frequency).
**Example 1:**
**Input:** s = "abacbc "
**Output:** true
**Explanation:** The character... | Note that the operations given describe getting the previous permutation of s To solve this problem you need to solve every suffix separately |
Simple one-liner with Counter | check-if-all-characters-have-equal-number-of-occurrences | 0 | 1 | # Intuition\nUse Counter()\n\n# Approach\nIff string is good then there is only one frequency\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def areOccurrencesEqual(self, s: str) -> bool:\n return len(set(Counter(s).values())) == 1\n``` | 2 | Given a string `s`, return `true` _if_ `s` _is a **good** string, or_ `false` _otherwise_.
A string `s` is **good** if **all** the characters that appear in `s` have the **same** number of occurrences (i.e., the same frequency).
**Example 1:**
**Input:** s = "abacbc "
**Output:** true
**Explanation:** The character... | Note that the operations given describe getting the previous permutation of s To solve this problem you need to solve every suffix separately |
Beginners method | One liner | python | check-if-all-characters-have-equal-number-of-occurrences | 0 | 1 | The key is using length to check if theres a non dup\n\n# Code\n```\nclass Solution:\n def areOccurrencesEqual(self, s: str) -> bool:\n return len(set(collections.Counter(s).values()))==1\n``` | 2 | Given a string `s`, return `true` _if_ `s` _is a **good** string, or_ `false` _otherwise_.
A string `s` is **good** if **all** the characters that appear in `s` have the **same** number of occurrences (i.e., the same frequency).
**Example 1:**
**Input:** s = "abacbc "
**Output:** true
**Explanation:** The character... | Note that the operations given describe getting the previous permutation of s To solve this problem you need to solve every suffix separately |
Two heaps simulation | the-number-of-the-smallest-unoccupied-chair | 0 | 1 | # Intuition\nUse to heaps to simulate the process\n\n# Approach\n1 sort the times array by arrival time, preserve the index of friend by creating a new list of tuples(arrival, leave, index)\n2 use two heaps, occupied and available to simulate the process\n3 when the targetFriend arrives (index == targetFriend), return ... | 0 | There is a party where `n` friends numbered from `0` to `n - 1` are attending. There is an **infinite** number of chairs in this party that are numbered from `0` to `infinity`. When a friend arrives at the party, they sit on the unoccupied chair with the **smallest number**.
* For example, if chairs `0`, `1`, and `5... | null |
Simulation: 6-Line Python Solution | the-number-of-the-smallest-unoccupied-chair | 0 | 1 | # Notes\n* `available` is a **min heap** of all available seat numbers. `i.e., 0, ... n`, where `n` is the length of `times` array, or the maximum possible seats.\n* `leave_times` is a **min heap** of (time when a person will leave, seat number assigned to this person).\n\n\n# Code\n```python3\ndef smallestChair(self, ... | 3 | There is a party where `n` friends numbered from `0` to `n - 1` are attending. There is an **infinite** number of chairs in this party that are numbered from `0` to `infinity`. When a friend arrives at the party, they sit on the unoccupied chair with the **smallest number**.
* For example, if chairs `0`, `1`, and `5... | null |
Python - Simple Heap Solution with Explanation | the-number-of-the-smallest-unoccupied-chair | 0 | 1 | **Explanation:**\n* Put all arrivals in one heap and all departures in another heap - this helps us to go by the chronogical order of time\n* If smallest time in arrivals heap is less than smallest time in departures heap, then pop from arrivals heap and occupy the 1st available table with the popped element. \n* If po... | 21 | There is a party where `n` friends numbered from `0` to `n - 1` are attending. There is an **infinite** number of chairs in this party that are numbered from `0` to `infinity`. When a friend arrives at the party, they sit on the unoccupied chair with the **smallest number**.
* For example, if chairs `0`, `1`, and `5... | null |
[Python3] sweeping | the-number-of-the-smallest-unoccupied-chair | 0 | 1 | \n```\nclass Solution:\n def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:\n vals = []\n for i, (arrival, leaving) in enumerate(times): \n vals.append((arrival, 1, i))\n vals.append((leaving, 0, i))\n \n k = 0 \n pq = [] # available se... | 21 | There is a party where `n` friends numbered from `0` to `n - 1` are attending. There is an **infinite** number of chairs in this party that are numbered from `0` to `infinity`. When a friend arrives at the party, they sit on the unoccupied chair with the **smallest number**.
* For example, if chairs `0`, `1`, and `5... | null |
The Number of the Smallest Unoccupied Chair|| Min Heaps || Heavily commented|| | the-number-of-the-smallest-unoccupied-chair | 0 | 1 | \n# Code\n```\nclass Solution:\n def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:\n import heapq as hq\n a=[]\n for i in range(len(times)):a.append([i,times[i][0],times[i][1]])\n a.sort(key=lambda x:[x[1],x[2]])\n """Instead of infinite by the logic at wor... | 0 | There is a party where `n` friends numbered from `0` to `n - 1` are attending. There is an **infinite** number of chairs in this party that are numbered from `0` to `infinity`. When a friend arrives at the party, they sit on the unoccupied chair with the **smallest number**.
* For example, if chairs `0`, `1`, and `5... | null |
[Python3] - Pushing Friends around - DoubleHeap | the-number-of-the-smallest-unoccupied-chair | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to keep track of the smallest chair available and keep track which friend has which chair and when he leaves.\n\nIn my head, this screams for thwo heaps and a simultion over time. Therefore, we first sort the friends in the order ... | 0 | There is a party where `n` friends numbered from `0` to `n - 1` are attending. There is an **infinite** number of chairs in this party that are numbered from `0` to `infinity`. When a friend arrives at the party, they sit on the unoccupied chair with the **smallest number**.
* For example, if chairs `0`, `1`, and `5... | null |
Python sorting + heap + map + solution | the-number-of-the-smallest-unoccupied-chair | 0 | 1 | ```\nclass Solution:\n def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:\n time_arr = []\n arrive, leave = 1, -1\n for idx, (arrive_time, leave_time) in enumerate(times):\n time_arr.append((arrive_time, arrive, idx))\n time_arr.append((leave_time, l... | 0 | There is a party where `n` friends numbered from `0` to `n - 1` are attending. There is an **infinite** number of chairs in this party that are numbered from `0` to `infinity`. When a friend arrives at the party, they sit on the unoccupied chair with the **smallest number**.
* For example, if chairs `0`, `1`, and `5... | null |
Python | Greedy | O(nlogn) | the-number-of-the-smallest-unoccupied-chair | 0 | 1 | # Code\n```\nclass Solution:\n def smallestChair(self, times: List[List[int]], target: int) -> int:\n n = len(times)\n h = [i for i in range(n)]\n events = []\n L, R = 1, 0\n for i, (s, e) in enumerate(times):\n events.append((s,L,i))\n events.append((e,R,i))\... | 0 | There is a party where `n` friends numbered from `0` to `n - 1` are attending. There is an **infinite** number of chairs in this party that are numbered from `0` to `infinity`. When a friend arrives at the party, they sit on the unoccupied chair with the **smallest number**.
* For example, if chairs `0`, `1`, and `5... | null |
Python (Simple Heap + Hashmap) | the-number-of-the-smallest-unoccupied-chair | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | There is a party where `n` friends numbered from `0` to `n - 1` are attending. There is an **infinite** number of chairs in this party that are numbered from `0` to `infinity`. When a friend arrives at the party, they sit on the unoccupied chair with the **smallest number**.
* For example, if chairs `0`, `1`, and `5... | null |
[Python] Easy solution in O(n*logn) with detailed explanation | describe-the-painting | 0 | 1 | ### Idea\nwe can iterate on coordinates of each `[start_i, end_i)` from small to large and maintain the current mixed color.\n\n### How can we maintain the mixed color?\nWe can do addition if the current coordinate is the beginning of a segment.\nIn contrast, We do subtraction if the current coordinate is the end of a ... | 136 | There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a **unique** color. You are given a 2D integer array `segments`, where `segments[i] = [starti, endi, colori]` represents the **half-closed segment**... | If the chosen substrings are of size larger than 1, then you can remove all but the first character from both substrings, and you'll get equal substrings of size 1, with the same a but less j. Hence, it's always optimal to choose substrings of size 1. If you choose a specific letter, then it's optimal to choose its fir... |
Line Sweep | describe-the-painting | 1 | 1 | We can use the line sweep approach to compute the sum (color mix) for each point. We use this line to check when a sum changes (a segment starts or finishes) and describe each mix. But there is a catch: different colors could produce the same sum. \n\nI was puzzled for a moment, and then I noticed that the color for ea... | 72 | There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a **unique** color. You are given a 2D integer array `segments`, where `segments[i] = [starti, endi, colori]` represents the **half-closed segment**... | If the chosen substrings are of size larger than 1, then you can remove all but the first character from both substrings, and you'll get equal substrings of size 1, with the same a but less j. Hence, it's always optimal to choose substrings of size 1. If you choose a specific letter, then it's optimal to choose its fir... |
[Python 3] - Difference Array + Sweep Line | describe-the-painting | 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... | 4 | There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a **unique** color. You are given a 2D integer array `segments`, where `segments[i] = [starti, endi, colori]` represents the **half-closed segment**... | If the chosen substrings are of size larger than 1, then you can remove all but the first character from both substrings, and you'll get equal substrings of size 1, with the same a but less j. Hence, it's always optimal to choose substrings of size 1. If you choose a specific letter, then it's optimal to choose its fir... |
[Python3] sweeping again | describe-the-painting | 0 | 1 | \n```\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n vals = []\n for start, end, color in segments: \n vals.append((start, +color))\n vals.append((end, -color))\n \n ans = []\n prefix = prev = 0 \n for x, c i... | 14 | There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a **unique** color. You are given a 2D integer array `segments`, where `segments[i] = [starti, endi, colori]` represents the **half-closed segment**... | If the chosen substrings are of size larger than 1, then you can remove all but the first character from both substrings, and you'll get equal substrings of size 1, with the same a but less j. Hence, it's always optimal to choose substrings of size 1. If you choose a specific letter, then it's optimal to choose its fir... |
🐍 O(nlogn) || Clean and Concise || 97% faster || Well-Explained with Example 📌📌 | describe-the-painting | 0 | 1 | ## IDEA :\nWe are finding all the starting and ending points. These points score we are storing in our dictinoary and after sorting all the poiints we are making our result array.\n\nEg: segments = [[1,7,9],[6,8,15],[8,10,7]]\nThere are 5 coordinates get involved. 1, 6, 7, 8, 10 respetively.\n* At coordinate 1, only th... | 11 | There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a **unique** color. You are given a 2D integer array `segments`, where `segments[i] = [starti, endi, colori]` represents the **half-closed segment**... | If the chosen substrings are of size larger than 1, then you can remove all but the first character from both substrings, and you'll get equal substrings of size 1, with the same a but less j. Hence, it's always optimal to choose substrings of size 1. If you choose a specific letter, then it's optimal to choose its fir... |
Python, beats 98% 10 lines. | describe-the-painting | 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. -->\nDefine list of breaking points, calculate effective color as aggretable meausure which changes at breaking points.\n\n# Complexity\n- Time complexity:\n<!-- Add your t... | 0 | There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a **unique** color. You are given a 2D integer array `segments`, where `segments[i] = [starti, endi, colori]` represents the **half-closed segment**... | If the chosen substrings are of size larger than 1, then you can remove all but the first character from both substrings, and you'll get equal substrings of size 1, with the same a but less j. Hence, it's always optimal to choose substrings of size 1. If you choose a specific letter, then it's optimal to choose its fir... |
Solution with Monotonic Stack in Python3 / TypeScript | number-of-visible-people-in-a-queue | 0 | 1 | # Intuition\nHere we have:\n- list of `heights`, a particular `heights[i]`\n- our goal is find for each `heights[i]` **HOW much** other persons from right we could see, and represent it in a list of **visible persons**\n\nOften it helps to iterate **not only** from `left` to `right`, but **vice-versa**.\nThis\'ll be **... | 1 | There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person.
A person can **see** another person to their right in the queue if everybody in between is ... | It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence |
Solution with Monotonic Stack in Python3 / TypeScript | number-of-visible-people-in-a-queue | 0 | 1 | # Intuition\nHere we have:\n- list of `heights`, a particular `heights[i]`\n- our goal is find for each `heights[i]` **HOW much** other persons from right we could see, and represent it in a list of **visible persons**\n\nOften it helps to iterate **not only** from `left` to `right`, but **vice-versa**.\nThis\'ll be **... | 1 | Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_.
**Example 1:**
**Input:** root1 = \[2,1,4\], root2 = \[1,0,3\]
**Output:** \[0,1,1,2,3,4\]
**Example 2:**
**Input:** root1 = \[1,null,8\], root2 = \[8,1\]
**Output:** \[1,1,8... | How to solve this problem in quadratic complexity ? For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found. Since the limits are high, you need a linear solution. Use a stack to keep the values of the array sorted as you iterate the array from the end to the start... |
Python 3 || 8 lines, stack, w/example || T/M: 88% / 72% | number-of-visible-people-in-a-queue | 0 | 1 | ```\nclass Solution: # *\n def canSeePersonsCount(self, heights: List[int]) -> List[int]: # * *\n # * *\n ... | 4 | There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person.
A person can **see** another person to their right in the queue if everybody in between is ... | It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence |
Python 3 || 8 lines, stack, w/example || T/M: 88% / 72% | number-of-visible-people-in-a-queue | 0 | 1 | ```\nclass Solution: # *\n def canSeePersonsCount(self, heights: List[int]) -> List[int]: # * *\n # * *\n ... | 4 | Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_.
**Example 1:**
**Input:** root1 = \[2,1,4\], root2 = \[1,0,3\]
**Output:** \[0,1,1,2,3,4\]
**Example 2:**
**Input:** root1 = \[1,null,8\], root2 = \[8,1\]
**Output:** \[1,1,8... | How to solve this problem in quadratic complexity ? For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found. Since the limits are high, you need a linear solution. Use a stack to keep the values of the array sorted as you iterate the array from the end to the start... |
[Java/Python 3] Monotonic stack w/ 18 similar problems, brief explanation and analysis. | number-of-visible-people-in-a-queue | 1 | 1 | **Method 1: reverse traversal - save heights into stack** \n\n**Intuition**\nSince we see from left to right and can only see any one higher than the persons between them, it looks simpler to traverse reversely (than from left to right) and use monotonic stack to save heights.\n\nBy keep popping out of stack the higher... | 50 | There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person.
A person can **see** another person to their right in the queue if everybody in between is ... | It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence |
[Java/Python 3] Monotonic stack w/ 18 similar problems, brief explanation and analysis. | number-of-visible-people-in-a-queue | 1 | 1 | **Method 1: reverse traversal - save heights into stack** \n\n**Intuition**\nSince we see from left to right and can only see any one higher than the persons between them, it looks simpler to traverse reversely (than from left to right) and use monotonic stack to save heights.\n\nBy keep popping out of stack the higher... | 50 | Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_.
**Example 1:**
**Input:** root1 = \[2,1,4\], root2 = \[1,0,3\]
**Output:** \[0,1,1,2,3,4\]
**Example 2:**
**Input:** root1 = \[1,null,8\], root2 = \[8,1\]
**Output:** \[1,1,8... | How to solve this problem in quadratic complexity ? For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found. Since the limits are high, you need a linear solution. Use a stack to keep the values of the array sorted as you iterate the array from the end to the start... |
✔ Python3 Solution | O(n) | Stack | number-of-visible-people-in-a-queue | 0 | 1 | `Time Complexity` : `O(n)`\n```\nclass Solution:\n def canSeePersonsCount(self, A):\n n = len(A)\n stack, res = [], [0] * n\n for i in range(n - 1, -1, -1):\n while stack and stack[-1] <= A[i]:\n stack.pop()\n res[i] += 1\n if stack: res[i] += ... | 1 | There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person.
A person can **see** another person to their right in the queue if everybody in between is ... | It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence |
✔ Python3 Solution | O(n) | Stack | number-of-visible-people-in-a-queue | 0 | 1 | `Time Complexity` : `O(n)`\n```\nclass Solution:\n def canSeePersonsCount(self, A):\n n = len(A)\n stack, res = [], [0] * n\n for i in range(n - 1, -1, -1):\n while stack and stack[-1] <= A[i]:\n stack.pop()\n res[i] += 1\n if stack: res[i] += ... | 1 | Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_.
**Example 1:**
**Input:** root1 = \[2,1,4\], root2 = \[1,0,3\]
**Output:** \[0,1,1,2,3,4\]
**Example 2:**
**Input:** root1 = \[1,null,8\], root2 = \[8,1\]
**Output:** \[1,1,8... | How to solve this problem in quadratic complexity ? For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found. Since the limits are high, you need a linear solution. Use a stack to keep the values of the array sorted as you iterate the array from the end to the start... |
[Python3] mono-stack | number-of-visible-people-in-a-queue | 0 | 1 | \n```\nclass Solution:\n def canSeePersonsCount(self, heights: List[int]) -> List[int]:\n ans = [0]*len(heights)\n stack = [] # mono-stack \n for i in reversed(range(len(heights))): \n while stack and stack[-1] <= heights[i]: \n ans[i] += 1\n stack.pop()\... | 10 | There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person.
A person can **see** another person to their right in the queue if everybody in between is ... | It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence |
[Python3] mono-stack | number-of-visible-people-in-a-queue | 0 | 1 | \n```\nclass Solution:\n def canSeePersonsCount(self, heights: List[int]) -> List[int]:\n ans = [0]*len(heights)\n stack = [] # mono-stack \n for i in reversed(range(len(heights))): \n while stack and stack[-1] <= heights[i]: \n ans[i] += 1\n stack.pop()\... | 10 | Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_.
**Example 1:**
**Input:** root1 = \[2,1,4\], root2 = \[1,0,3\]
**Output:** \[0,1,1,2,3,4\]
**Example 2:**
**Input:** root1 = \[1,null,8\], root2 = \[8,1\]
**Output:** \[1,1,8... | How to solve this problem in quadratic complexity ? For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found. Since the limits are high, you need a linear solution. Use a stack to keep the values of the array sorted as you iterate the array from the end to the start... |
Python3 | O(n) using stack | with comments | number-of-visible-people-in-a-queue | 0 | 1 | # Code\n```\nclass Solution:\n def canSeePersonsCount(self, heights: List[int]) -> List[int]:\n n = len(heights)\n visible_people = [1] * n\n stack=[]\n for i in range(n-1, -1, -1):\n # set the counter to 0\n count = 0\n while stack and heights[stack[-1]] ... | 1 | There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person.
A person can **see** another person to their right in the queue if everybody in between is ... | It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence |
Python3 | O(n) using stack | with comments | number-of-visible-people-in-a-queue | 0 | 1 | # Code\n```\nclass Solution:\n def canSeePersonsCount(self, heights: List[int]) -> List[int]:\n n = len(heights)\n visible_people = [1] * n\n stack=[]\n for i in range(n-1, -1, -1):\n # set the counter to 0\n count = 0\n while stack and heights[stack[-1]] ... | 1 | Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_.
**Example 1:**
**Input:** root1 = \[2,1,4\], root2 = \[1,0,3\]
**Output:** \[0,1,1,2,3,4\]
**Example 2:**
**Input:** root1 = \[1,null,8\], root2 = \[8,1\]
**Output:** \[1,1,8... | How to solve this problem in quadratic complexity ? For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found. Since the limits are high, you need a linear solution. Use a stack to keep the values of the array sorted as you iterate the array from the end to the start... |
Simple python solution for beginners | sum-of-digits-of-string-after-convert | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You are given a string `s` consisting of lowercase English letters, and an integer `k`.
First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum ... | Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user. |
Python Easy Solution || 100% || | sum-of-digits-of-string-after-convert | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You are given a string `s` consisting of lowercase English letters, and an integer `k`.
First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum ... | Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user. |
Simple code beat 90% of python users, Beginner friendly | sum-of-digits-of-string-after-convert | 0 | 1 | # Code\n```\nclass Solution:\n def getLucky(self, s: str, k: int) -> int:\n num=\'\'\n for i in range(len(s)):\n num+=str(ord(s[i])-ord(\'a\')+1)\n \n for i in range(k):\n count=0\n for j in range(len(num)):\n count+=int(num[j]) \n ... | 1 | You are given a string `s` consisting of lowercase English letters, and an integer `k`.
First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum ... | Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user. |
Python Very Easy Solution | sum-of-digits-of-string-after-convert | 0 | 1 | # Code\n```\nclass Solution:\n def digitSum(self, n: int) -> int:\n tot=0\n while(n>0):\n tot+=n%10\n n//=10\n return tot\n \n def getLucky(self, s: str, k: int) -> int:\n num=""\n for i in s:\n num+=str(ord(i)-96)\n num=int(num)\n ... | 1 | You are given a string `s` consisting of lowercase English letters, and an integer `k`.
First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum ... | Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user. |
sum-of-digits-of-string-after-convert | sum-of-digits-of-string-after-convert | 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. -->\nUsing dictionary...\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 h... | 1 | You are given a string `s` consisting of lowercase English letters, and an integer `k`.
First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum ... | Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user. |
Beats 90 %!!! 35 ms!!!Python solution -_- | sum-of-digits-of-string-after-convert | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 5 | You are given a string `s` consisting of lowercase English letters, and an integer `k`.
First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum ... | Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user. |
python3 code | sum-of-digits-of-string-after-convert | 0 | 1 | # Code\n```\nclass Solution:\n def convert(self, s):\n converted = ""\n alphabet = "abcdefghijklmnopqrstuvwxyz"\n for char in s:\n converted += str(alphabet.index(char) + 1)\n return converted\n def getSum(self, converted):\n result = 0\n for char in str(conver... | 4 | You are given a string `s` consisting of lowercase English letters, and an integer `k`.
First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum ... | Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user. |
[Python3] simulation | sum-of-digits-of-string-after-convert | 0 | 1 | \n```\nclass Solution:\n def getLucky(self, s: str, k: int) -> int:\n s = "".join(str(ord(ch) - 96) for ch in s)\n for _ in range(k): \n x = sum(int(ch) for ch in s)\n s = str(x)\n return x \n```\n\n```\nclass Solution:\n def getLucky(self, s: str, k: int) -> int:\n ... | 5 | You are given a string `s` consisting of lowercase English letters, and an integer `k`.
First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum ... | Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user. |
[Python3] greedy | largest-number-after-mutating-substring | 0 | 1 | \n```\nclass Solution:\n def maximumNumber(self, num: str, change: List[int]) -> str:\n num = list(num)\n on = False \n for i, ch in enumerate(num): \n x = int(ch)\n if x < change[x]: \n on = True\n num[i] = str(change[x])\n elif x >... | 7 | You are given a string `num`, which represents a large integer. You are also given a **0-indexed** integer array `change` of length `10` that maps each digit `0-9` to another digit. More formally, digit `d` maps to digit `change[d]`.
You may **choose** to **mutate a single substring** of `num`. To mutate a substring, ... | Go through each element and test the optimal replacements. There are only 2 possible replacements for each element (higher and lower) that are optimal. |
python3 solution | largest-number-after-mutating-substring | 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 `num`, which represents a large integer. You are also given a **0-indexed** integer array `change` of length `10` that maps each digit `0-9` to another digit. More formally, digit `d` maps to digit `change[d]`.
You may **choose** to **mutate a single substring** of `num`. To mutate a substring, ... | Go through each element and test the optimal replacements. There are only 2 possible replacements for each element (higher and lower) that are optimal. |
largest-number-after-mutating-substring | largest-number-after-mutating-substring | 0 | 1 | # Code\n```\nclass Solution:\n def maximumNumber(self, num: str, change: List[int]) -> str:\n s = ""\n count = 0\n count1 = 0\n for i in num:\n if int(i) <= change[int(i)] and count == 0:\n s+= str(change[int(i)])\n count1+=1 \n el... | 0 | You are given a string `num`, which represents a large integer. You are also given a **0-indexed** integer array `change` of length `10` that maps each digit `0-9` to another digit. More formally, digit `d` maps to digit `change[d]`.
You may **choose** to **mutate a single substring** of `num`. To mutate a substring, ... | Go through each element and test the optimal replacements. There are only 2 possible replacements for each element (higher and lower) that are optimal. |
Python easy solution | largest-number-after-mutating-substring | 0 | 1 | ```\nclass Solution:\n def maximumNumber(self, num: str, change: List[int]) -> str:\n res = \'\'\n d = {str(idx): val for idx, val in enumerate(change)}\n changed = False\n for idx, digit in enumerate(num):\n if d[digit] > int(digit):\n res += str(d[digit])\n ... | 0 | You are given a string `num`, which represents a large integer. You are also given a **0-indexed** integer array `change` of length `10` that maps each digit `0-9` to another digit. More formally, digit `d` maps to digit `change[d]`.
You may **choose** to **mutate a single substring** of `num`. To mutate a substring, ... | Go through each element and test the optimal replacements. There are only 2 possible replacements for each element (higher and lower) that are optimal. |
[Python3] permutations | maximum-compatibility-score-sum | 0 | 1 | **Approach 1 - brute force**\n```\nclass Solution:\n def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n m = len(students)\n \n score = [[0]*m for _ in range(m)]\n for i in range(m): \n for j in range(m): \n score[i][j] = ... | 20 | There is a survey that consists of `n` questions where each question's answer is either `0` (no) or `1` (yes).
The survey was given to `m` students numbered from `0` to `m - 1` and `m` mentors numbered from `0` to `m - 1`. The answers of the students are represented by a 2D integer array `students` where `students[i]`... | Think of how to check if a number x is a gcd of a subsequence. If there is such subsequence, then all of it will be divisible by x. Moreover, if you divide each number in the subsequence by x , then the gcd of the resulting numbers will be 1. Adding a number to a subsequence cannot increase its gcd. So, if there is a v... |
[Python3] Intuitive Backtracking solution | maximum-compatibility-score-sum | 0 | 1 | \n# Code\n```python3\nclass Solution:\n def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n \n result = 0\n\n def get_score(l1, l2):\n score = 0\n index = len(l1) - 1\n while index >= 0:\n if l1[index] == l2... | 0 | There is a survey that consists of `n` questions where each question's answer is either `0` (no) or `1` (yes).
The survey was given to `m` students numbered from `0` to `m - 1` and `m` mentors numbered from `0` to `m - 1`. The answers of the students are represented by a 2D integer array `students` where `students[i]`... | Think of how to check if a number x is a gcd of a subsequence. If there is such subsequence, then all of it will be divisible by x. Moreover, if you divide each number in the subsequence by x , then the gcd of the resulting numbers will be 1. Adding a number to a subsequence cannot increase its gcd. So, if there is a v... |
Easy to understand solution written in Python using Backtracking and Memoization with bit masking | maximum-compatibility-score-sum | 0 | 1 | # Intuition\nWhen I first read this problem, my first intuition is to draw out the decision tree to see what the decisions are for each state.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor each student, we will try to assign to one mentor if that mentor has not yet been assigned by any oth... | 0 | There is a survey that consists of `n` questions where each question's answer is either `0` (no) or `1` (yes).
The survey was given to `m` students numbered from `0` to `m - 1` and `m` mentors numbered from `0` to `m - 1`. The answers of the students are represented by a 2D integer array `students` where `students[i]`... | Think of how to check if a number x is a gcd of a subsequence. If there is such subsequence, then all of it will be divisible by x. Moreover, if you divide each number in the subsequence by x , then the gcd of the resulting numbers will be 1. Adding a number to a subsequence cannot increase its gcd. So, if there is a v... |
[Python3] serialize sub-trees | delete-duplicate-folders-in-system | 0 | 1 | \n```\nclass Solution:\n def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:\n paths.sort()\n \n tree = {"#": -1}\n for i, path in enumerate(paths): \n node = tree\n for x in path: node = node.setdefault(x, {})\n node["#"] = i\n ... | 4 | Due to a bug, there are many duplicate folders in a file system. You are given a 2D array `paths`, where `paths[i]` is an array representing an absolute path to the `ith` folder in the file system.
* For example, `[ "one ", "two ", "three "]` represents the path `"/one/two/three "`.
Two folders (not necessarily on ... | null |
python dfs + trie + hasmap | delete-duplicate-folders-in-system | 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 | Due to a bug, there are many duplicate folders in a file system. You are given a 2D array `paths`, where `paths[i]` is an array representing an absolute path to the `ith` folder in the file system.
* For example, `[ "one ", "two ", "three "]` represents the path `"/one/two/three "`.
Two folders (not necessarily on ... | null |
Python solution: JSON-style hashing of all subtrees | delete-duplicate-folders-in-system | 0 | 1 | # Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\nInitially I tried to build a Trie with the words reversed, but very soon I found it gives wrong answers. And there are interesting testcases which essentially requires serialization of subtrees\r\n# Approach\r\n<!-- Describe your appr... | 0 | Due to a bug, there are many duplicate folders in a file system. You are given a 2D array `paths`, where `paths[i]` is an array representing an absolute path to the `ith` folder in the file system.
* For example, `[ "one ", "two ", "three "]` represents the path `"/one/two/three "`.
Two folders (not necessarily on ... | null |
Python Clean sultion( DFS, hashmaps, serialization) with explaination | delete-duplicate-folders-in-system | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis code is devised to address the problem of identifying and removing duplicate folder structures within a given set of folder paths. A folder structure is considered duplicate if there exists another folder structure with the exact sam... | 0 | Due to a bug, there are many duplicate folders in a file system. You are given a 2D array `paths`, where `paths[i]` is an array representing an absolute path to the `ith` folder in the file system.
* For example, `[ "one ", "two ", "three "]` represents the path `"/one/two/three "`.
Two folders (not necessarily on ... | null |
Python3 with tree hash | delete-duplicate-folders-in-system | 0 | 1 | ```\nimport collections\nfrom typing import List\nfrom sortedcontainers import SortedDict\n\n\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.children = SortedDict()\n\n\nclass Solution:\n def __init__(self):\n self.key2Id = {}\n self.key2Count = collections.default... | 0 | Due to a bug, there are many duplicate folders in a file system. You are given a 2D array `paths`, where `paths[i]` is an array representing an absolute path to the `ith` folder in the file system.
* For example, `[ "one ", "two ", "three "]` represents the path `"/one/two/three "`.
Two folders (not necessarily on ... | null |
Python3 solution - clean code (trie, dfs and Hashmap) | delete-duplicate-folders-in-system | 0 | 1 | ```\nclass TrieNode:\n def __init__(self, char):\n self.children = {}\n self.is_end = False\n self.child_hash = ""\n self.char = char\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode("/")\n self.hashmap = collections.defaultdict(int)\n self.duplicates = ... | 1 | Due to a bug, there are many duplicate folders in a file system. You are given a 2D array `paths`, where `paths[i]` is an array representing an absolute path to the `ith` folder in the file system.
* For example, `[ "one ", "two ", "three "]` represents the path `"/one/two/three "`.
Two folders (not necessarily on ... | null |
Beats 62.32% || Three Divisors | three-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)$$ --... | 1 | Given an integer `n`, return `true` _if_ `n` _has **exactly three positive divisors**. Otherwise, return_ `false`.
An integer `m` is a **divisor** of `n` if there exists an integer `k` such that `n = k * m`.
**Example 1:**
**Input:** n = 2
**Output:** false
**Explantion:** 2 has only two divisors: 1 and 2.
**Exampl... | At a given point, there are only 3 possible states for where the frog can be. Check all the ways to move from one point to the next and update the minimum side jumps for each lane. |
Simple Solution Using Loop & Condition | three-divisors | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def isThree(self, n: int) -> bool:\n new=[]\n for i in range(1,n+1):\n if n%i==0:\n new.append(i)\n return len(new)==3\n```\nHope you like the solution and your comments are welcomed :). | 1 | Given an integer `n`, return `true` _if_ `n` _has **exactly three positive divisors**. Otherwise, return_ `false`.
An integer `m` is a **divisor** of `n` if there exists an integer `k` such that `n = k * m`.
**Example 1:**
**Input:** n = 2
**Output:** false
**Explantion:** 2 has only two divisors: 1 and 2.
**Exampl... | At a given point, there are only 3 possible states for where the frog can be. Check all the ways to move from one point to the next and update the minimum side jumps for each lane. |
[Python3] 1-line | three-divisors | 0 | 1 | \n```\nclass Solution:\n def isThree(self, n: int) -> bool:\n return sum(n%i == 0 for i in range(1, n+1)) == 3\n```\n\nAdding `O(N^1/4)` solution \n```\nclass Solution:\n def isThree(self, n: int) -> bool:\n if n == 1: return False # edge case \n \n x = int(sqrt(n))\n if x*x != ... | 17 | Given an integer `n`, return `true` _if_ `n` _has **exactly three positive divisors**. Otherwise, return_ `false`.
An integer `m` is a **divisor** of `n` if there exists an integer `k` such that `n = k * m`.
**Example 1:**
**Input:** n = 2
**Output:** false
**Explantion:** 2 has only two divisors: 1 and 2.
**Exampl... | At a given point, there are only 3 possible states for where the frog can be. Check all the ways to move from one point to the next and update the minimum side jumps for each lane. |
Python Easy Solution | three-divisors | 0 | 1 | # Code\n```\nclass Solution:\n def isThree(self, n: int) -> bool:\n cnt=2\n for i in range(2,n//2+1):\n if n%i==0:\n cnt+=1\n if cnt>3:\n return 0\n if cnt!=3:\n return 0\n return 1\n``` | 2 | Given an integer `n`, return `true` _if_ `n` _has **exactly three positive divisors**. Otherwise, return_ `false`.
An integer `m` is a **divisor** of `n` if there exists an integer `k` such that `n = k * m`.
**Example 1:**
**Input:** n = 2
**Output:** false
**Explantion:** 2 has only two divisors: 1 and 2.
**Exampl... | At a given point, there are only 3 possible states for where the frog can be. Check all the ways to move from one point to the next and update the minimum side jumps for each lane. |
Explained Python Solution using primes, O(1) | Faster than 99% | three-divisors | 0 | 1 | # Explained Python Solution using primes, O(1) | Faster than 99%\n\n**Runtime: 24 ms, faster than 99% of Python3 online submissions for Three Divisors.\nMemory Usage: 14.2 MB, less than 74% of Python3 online submissions for Three Divisors.**\n\n**Original Program**\n```\nimport math\nclass Solution:\n def isThree(se... | 7 | Given an integer `n`, return `true` _if_ `n` _has **exactly three positive divisors**. Otherwise, return_ `false`.
An integer `m` is a **divisor** of `n` if there exists an integer `k` such that `n = k * m`.
**Example 1:**
**Input:** n = 2
**Output:** false
**Explantion:** 2 has only two divisors: 1 and 2.
**Exampl... | At a given point, there are only 3 possible states for where the frog can be. Check all the ways to move from one point to the next and update the minimum side jumps for each lane. |
[Python] Solution with detailed explanation & proof & common failure analysis | maximum-number-of-weeks-for-which-you-can-work | 0 | 1 | \n## Solution 1\nThanks [@pgthebigshot](https://leetcode.com/pgthebigshot/) for providing another solution for easier understanding. \nI make some images to explain the idea.\n\n### Idea\nWe can separate projects to two sets.\n1. The project with the most milestones\n2. The rest of the projects.\n\nIf `sum(milestones e... | 243 | There are `n` projects numbered from `0` to `n - 1`. You are given an integer array `milestones` where each `milestones[i]` denotes the number of milestones the `ith` project has.
You can work on the projects following these two rules:
* Every week, you will finish **exactly one** milestone of **one** project. You ... | At each query, try to save and update the sum of the elements needed to calculate MKAverage. You can use BSTs for fast insertion and deletion of the elements. |
O(n) | maximum-number-of-weeks-for-which-you-can-work | 1 | 1 | I got a working solution using a max heap, then tried to optimized it to push through TLE. No luck. \n\nThis prolem seems to requrie prior knowledge or a very good intuition:\n\n> We can complete all milestones for all projects, unless one project has more milestones then all other projects combined.\n> \n> For the lat... | 50 | There are `n` projects numbered from `0` to `n - 1`. You are given an integer array `milestones` where each `milestones[i]` denotes the number of milestones the `ith` project has.
You can work on the projects following these two rules:
* Every week, you will finish **exactly one** milestone of **one** project. You ... | At each query, try to save and update the sum of the elements needed to calculate MKAverage. You can use BSTs for fast insertion and deletion of the elements. |
[Java/Python 3] 3/2 line greedy O(n) code w/ brief explanation. | maximum-number-of-weeks-for-which-you-can-work | 1 | 1 | **Intuition:**\nAccording to the rule "cannot work on two milestones from the same project for two consecutive weeks.", we at least need to avoid the consecutive working on the project with the maximum milestones, which are most likely to be involved to violate the rule.\n\n----\n\n1. If the `max` of the `milestones` i... | 9 | There are `n` projects numbered from `0` to `n - 1`. You are given an integer array `milestones` where each `milestones[i]` denotes the number of milestones the `ith` project has.
You can work on the projects following these two rules:
* Every week, you will finish **exactly one** milestone of **one** project. You ... | At each query, try to save and update the sum of the elements needed to calculate MKAverage. You can use BSTs for fast insertion and deletion of the elements. |
Very easy python solution | maximum-number-of-weeks-for-which-you-can-work | 0 | 1 | ```\n def numberOfWeeks(self, milestones: List[int]) -> int:\n \n n=len(milestones)\n if n==1:\n return 1\n s=sum(milestones)\n \n if max(milestones)>s-max(milestones)+1:\n return 2*(s-max(milestones))+1\n return s | 2 | There are `n` projects numbered from `0` to `n - 1`. You are given an integer array `milestones` where each `milestones[i]` denotes the number of milestones the `ith` project has.
You can work on the projects following these two rules:
* Every week, you will finish **exactly one** milestone of **one** project. You ... | At each query, try to save and update the sum of the elements needed to calculate MKAverage. You can use BSTs for fast insertion and deletion of the elements. |
Python with details. | maximum-number-of-weeks-for-which-you-can-work | 0 | 1 | Initially I also tried the approach with decrementing the every project with maxiumum number of milestones.\n\nIt works but the complexity is awfull.\n\n\n# Approach\n\nThen used approach with simple logic.\nIf the maximum number of milstones is less or equal than sum of milestones - maximum S - M >= M then all milesto... | 0 | There are `n` projects numbered from `0` to `n - 1`. You are given an integer array `milestones` where each `milestones[i]` denotes the number of milestones the `ith` project has.
You can work on the projects following these two rules:
* Every week, you will finish **exactly one** milestone of **one** project. You ... | At each query, try to save and update the sum of the elements needed to calculate MKAverage. You can use BSTs for fast insertion and deletion of the elements. |
Python || Sort | maximum-number-of-weeks-for-which-you-can-work | 0 | 1 | # Intuition\n- If you can find the pairs for the max element in the array you are done, because you can insert any number of elements in between the pairs.\n\n# Approach\n- Sort the array\n- Get the max of the array, try and get the pairs for the maximum element\n- Once done return sum(milestones)\n- If we are not able... | 0 | There are `n` projects numbered from `0` to `n - 1`. You are given an integer array `milestones` where each `milestones[i]` denotes the number of milestones the `ith` project has.
You can work on the projects following these two rules:
* Every week, you will finish **exactly one** milestone of **one** project. You ... | At each query, try to save and update the sum of the elements needed to calculate MKAverage. You can use BSTs for fast insertion and deletion of the elements. |
Python: Math problem | maximum-number-of-weeks-for-which-you-can-work | 0 | 1 | # Intuition\nthis is a hell problem, i figure it by using math finally\n\n# Approach\n1. we know that the max of the work can not more than -> (sum of array - max num in the arry) multiple by 2 plus 1 -> (sum(array) - max_num) * 2 + 1\n\n2. then we need to find the amount to deduct from total, as the max deduct amt sho... | 0 | There are `n` projects numbered from `0` to `n - 1`. You are given an integer array `milestones` where each `milestones[i]` denotes the number of milestones the `ith` project has.
You can work on the projects following these two rules:
* Every week, you will finish **exactly one** milestone of **one** project. You ... | At each query, try to save and update the sum of the elements needed to calculate MKAverage. You can use BSTs for fast insertion and deletion of the elements. |
[Java/Python 3] From O(n ^ (1 / 3)) to O(log(n)), easy codes w/ brief explanation & analysis. | minimum-garden-perimeter-to-collect-enough-apples | 1 | 1 | **Method 1:**\n\nDivide into 3 parts: axis, corner and other:\n\nUse `i`, `corner` and `other` to denote the number of apples on each half axis, each corner and other parts, respectively.\n\nObviously, for any given `i`, each half axis has `i` apples; each of the 4 corners has `2 * i` apples, and the rest part (quadra... | 10 | In a garden represented as an infinite 2D grid, there is an apple tree planted at **every** integer coordinate. The apple tree planted at an integer coordinate `(i, j)` has `|i| + |j|` apples growing on it.
You will buy an axis-aligned **square plot** of land that is centered at `(0, 0)`.
Given an integer `neededAppl... | We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.