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 3 || 4 lines, fixed window || T/M: 99% / 99%
check-if-there-is-a-valid-partition-for-the-array
0
1
We use a sliding window of fixed length 3, checking element by element, whether any one of the three conditions is satisfied.\n```\nclass Solution:\n def validPartition(self, nums: List[int]) -> bool:\n\n checks = (True, False, nums[0] == nums[1])\n\n for curr, prev1, prev2 in zip(nums[2:], nums[1:], n...
3
You are given a **0-indexed** integer array `nums`. You have to partition the array into one or more **contiguous** subarrays. We call a partition of the array **valid** if each of the obtained subarrays satisfies **one** of the following conditions: 1. The subarray consists of **exactly** `2` equal elements. For ex...
How can we use precalculation to efficiently calculate the average difference at an index? Create a prefix and/or suffix sum array.
O(1) space in-place solution that isn't in Editorial
check-if-there-is-a-valid-partition-for-the-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse dynamic programming to solve this one.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nNegate a number to mark a cell.\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$...
2
You are given a **0-indexed** integer array `nums`. You have to partition the array into one or more **contiguous** subarrays. We call a partition of the array **valid** if each of the obtained subarrays satisfies **one** of the following conditions: 1. The subarray consists of **exactly** `2` equal elements. For ex...
How can we use precalculation to efficiently calculate the average difference at an index? Create a prefix and/or suffix sum array.
Python3 Solution
check-if-there-is-a-valid-partition-for-the-array
0
1
\n```\nclass Solution:\n def validPartition(self, nums: List[int]) -> bool:\n n=len(nums)\n @cache\n def fn(index):\n if index==n:\n return True\n\n if index+1<n and nums[index]==nums[index+1] and fn(index+2):\n return True\n\n if in...
2
You are given a **0-indexed** integer array `nums`. You have to partition the array into one or more **contiguous** subarrays. We call a partition of the array **valid** if each of the obtained subarrays satisfies **one** of the following conditions: 1. The subarray consists of **exactly** `2` equal elements. For ex...
How can we use precalculation to efficiently calculate the average difference at an index? Create a prefix and/or suffix sum array.
Very Easy Code || Line by Line Explained || Memoization || C++ || java || Python
check-if-there-is-a-valid-partition-for-the-array
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nExplore all the options and if any option returns true then answer is true.\n\nFor detailed explanation you can refer to my youtube channel (Hindi Language) \nhttps://youtu.be/lxpa98WWB-k\nor link in my profile.Here,you can find any solut...
24
You are given a **0-indexed** integer array `nums`. You have to partition the array into one or more **contiguous** subarrays. We call a partition of the array **valid** if each of the obtained subarrays satisfies **one** of the following conditions: 1. The subarray consists of **exactly** `2` equal elements. For ex...
How can we use precalculation to efficiently calculate the average difference at an index? Create a prefix and/or suffix sum array.
Simple Recursion + Memoization solution Python 3 with comments! 😸
check-if-there-is-a-valid-partition-for-the-array
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 **0-indexed** integer array `nums`. You have to partition the array into one or more **contiguous** subarrays. We call a partition of the array **valid** if each of the obtained subarrays satisfies **one** of the following conditions: 1. The subarray consists of **exactly** `2` equal elements. For ex...
How can we use precalculation to efficiently calculate the average difference at an index? Create a prefix and/or suffix sum array.
🔥 Beats 85% | Clean Code | DP + Memoization | ⚡️C++, Rust, Go, Java, Python, Javascript
check-if-there-is-a-valid-partition-for-the-array
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUltra Instinct \u26A1\uFE0F\n# Approach\n<!-- Describe your approach to solving the problem. -->\nExplore all possibilities and memoize explored! \uD83D\uDDFA\uFE0F\uD83C\uDF0D\n# Complexity\n- Time complexity: $$O(N)$$\n<!-- Add your tim...
1
You are given a **0-indexed** integer array `nums`. You have to partition the array into one or more **contiguous** subarrays. We call a partition of the array **valid** if each of the obtained subarrays satisfies **one** of the following conditions: 1. The subarray consists of **exactly** `2` equal elements. For ex...
How can we use precalculation to efficiently calculate the average difference at an index? Create a prefix and/or suffix sum array.
DP
longest-ideal-subsequence
1
1
For character `s[i]`, `dp[s[i]]` indicates the longest subsequence that ends at that character.\n \nFor character `s[i + 1]`, `dp[s[i + 1]] = 1 + max(dp[reachable])`, where `abs(s[i + 1] - reachable) <= k`.\n\n**Python 3**\n```python\nclass Solution:\n def longestIdealString(self, s: str, k: int) -> int:\n ...
35
You are given a string `s` consisting of lowercase letters and an integer `k`. We call a string `t` **ideal** if the following conditions are satisfied: * `t` is a **subsequence** of the string `s`. * The absolute difference in the alphabet order of every two **adjacent** letters in `t` is less than or equal to `k...
null
[C++/Java/Python] Easy to understand
longest-ideal-subsequence
1
1
**Naive approach**: A brute force solution is to generate all the possible subsequences of various lengths and compute the maximum length of the valid subsequence. The time complexity will be exponential.\n\n**Efficient Approach**: An efficient approach is to use the concept **Dynamic Programming** \n\n* Create an arra...
9
You are given a string `s` consisting of lowercase letters and an integer `k`. We call a string `t` **ideal** if the following conditions are satisfied: * `t` is a **subsequence** of the string `s`. * The absolute difference in the alphabet order of every two **adjacent** letters in `t` is less than or equal to `k...
null
Python 3. O(n) Solution - DP
longest-ideal-subsequence
0
1
```\nclass Solution:\n def longestIdealString(self, s: str, k: int) -> int:\n \n # For storing the largest substring ending at that character \n psum=[0]*26\n ans=1\n for i in range(len(s)):\n element=ord(s[i])-97\n \n # Checking for k characters le...
1
You are given a string `s` consisting of lowercase letters and an integer `k`. We call a string `t` **ideal** if the following conditions are satisfied: * `t` is a **subsequence** of the string `s`. * The absolute difference in the alphabet order of every two **adjacent** letters in `t` is less than or equal to `k...
null
[Python3] simulation
largest-local-values-in-a-matrix
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/abc9891d642b2454c148af46a140ff3497f7ce3c) for solutions of weekly 306. \n\n```\nclass Solution:\n def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:\n n = len(grid)\n ans = [[0]*(n-2) for _ in range(n-2)]\n fo...
25
You are given an `n x n` integer matrix `grid`. Generate an integer matrix `maxLocal` of size `(n - 2) x (n - 2)` such that: * `maxLocal[i][j]` is equal to the **largest** value of the `3 x 3` matrix in `grid` centered around row `i + 1` and column `j + 1`. In other words, we want to find the largest value in ever...
null
🔥 [Python3] Short brute-force, using list comprehension
largest-local-values-in-a-matrix
0
1
```python3 []\nclass Solution:\n def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:\n N = len(grid)-2\n res = [[0] * N for _ in range(N)]\n for i,j in product(range(N), range(N)):\n res[i][j] = max(grid[r][c] for r, c in product(range(i, i+3), range(j, j+3)))\n\n ...
9
You are given an `n x n` integer matrix `grid`. Generate an integer matrix `maxLocal` of size `(n - 2) x (n - 2)` such that: * `maxLocal[i][j]` is equal to the **largest** value of the `3 x 3` matrix in `grid` centered around row `i + 1` and column `j + 1`. In other words, we want to find the largest value in ever...
null
✅Python || Easy Approach || Brute force
largest-local-values-in-a-matrix
0
1
```\nclass Solution:\n def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:\n\n n = len(grid)\n ans = []\n\n for i in range(n - 2):\n res = []\n\n for j in range(n - 2):\n k = []\n k.append(grid[i][j])\n k.append(gri...
16
You are given an `n x n` integer matrix `grid`. Generate an integer matrix `maxLocal` of size `(n - 2) x (n - 2)` such that: * `maxLocal[i][j]` is equal to the **largest** value of the `3 x 3` matrix in `grid` centered around row `i + 1` and column `j + 1`. In other words, we want to find the largest value in ever...
null
Python Elegant & Short | 100% faster
largest-local-values-in-a-matrix
0
1
![image](https://assets.leetcode.com/users/images/0a9a0d13-e9cb-430f-8777-e73df4685f7a_1660554242.9688396.png)\n\n\n```\nclass Solution:\n\t"""\n\tTime: O(n^2)\n\tMemory: O(1)\n\t"""\n\n\tdef largestLocal(self, grid: List[List[int]]) -> List[List[int]]:\n\t\tn = len(grid)\n\t\treturn [[self.local_max(grid, r, c, 1) f...
7
You are given an `n x n` integer matrix `grid`. Generate an integer matrix `maxLocal` of size `(n - 2) x (n - 2)` such that: * `maxLocal[i][j]` is equal to the **largest** value of the `3 x 3` matrix in `grid` centered around row `i + 1` and column `j + 1`. In other words, we want to find the largest value in ever...
null
✅ [Python] Two loop solution
largest-local-values-in-a-matrix
0
1
```\nclass Solution:\n def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:\n n = len(grid)\n matrix = [[1]* (n-2) for i in range(n-2)]\n for i in range(1, n - 1):\n for j in range(1, n - 1):\n matrix[i-1][j-1] = max(grid[i-1][j-1], grid[i-1][j], grid[i-1][...
8
You are given an `n x n` integer matrix `grid`. Generate an integer matrix `maxLocal` of size `(n - 2) x (n - 2)` such that: * `maxLocal[i][j]` is equal to the **largest** value of the `3 x 3` matrix in `grid` centered around row `i + 1` and column `j + 1`. In other words, we want to find the largest value in ever...
null
SIMPLE PYTHON SOLUTION
node-with-highest-edge-score
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nArray Traversal\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,...
1
You are given a directed graph with `n` nodes labeled from `0` to `n - 1`, where each node has **exactly one** outgoing edge. The graph is represented by a given **0-indexed** integer array `edges` of length `n`, where `edges[i]` indicates that there is a **directed** edge from node `i` to node `edges[i]`. The **edge...
null
[Java/Python 3] Iterative O(n) codes w/ brief explanation and analysis.
node-with-highest-edge-score
1
1
1. Traverse the input `edges`, acculumate the score for each edge-pointed node;\n2. Traverse the `scores` array and find the solution.\n\n**Note:** Java code need a `long` type `scores` array, otherwise it would cause `int` overflow that will result wrong answer.\n```java\n public int edgeScore(int[] edges) {\n ...
8
You are given a directed graph with `n` nodes labeled from `0` to `n - 1`, where each node has **exactly one** outgoing edge. The graph is represented by a given **0-indexed** integer array `edges` of length `n`, where `edges[i]` indicates that there is a **directed** edge from node `i` to node `edges[i]`. The **edge...
null
✅Python || Easy Approach || Hashmap
node-with-highest-edge-score
0
1
```\nclass Solution:\n def edgeScore(self, edges: List[int]) -> int:\n\n n = len(edges)\n cnt = defaultdict(int)\n ans = 0\n \n\t\t// we have the key stores the node edges[i], and the value indicates the edge score.\n for i in range(n):\n cnt[edges[i]] += i\n\n m ...
4
You are given a directed graph with `n` nodes labeled from `0` to `n - 1`, where each node has **exactly one** outgoing edge. The graph is represented by a given **0-indexed** integer array `edges` of length `n`, where `edges[i]` indicates that there is a **directed** edge from node `i` to node `edges[i]`. The **edge...
null
Python | Simple counting
node-with-highest-edge-score
0
1
```\nclass Solution:\n def edgeScore(self, edges: List[int]) -> int:\n n = len(edges)\n score = [0] * n\n \n for i, val in enumerate(edges):\n score[val] += i\n return score.index(max(score))\n```
2
You are given a directed graph with `n` nodes labeled from `0` to `n - 1`, where each node has **exactly one** outgoing edge. The graph is represented by a given **0-indexed** integer array `edges` of length `n`, where `edges[i]` indicates that there is a **directed** edge from node `i` to node `edges[i]`. The **edge...
null
Short and intuitive solution NO stack, just count and string.
construct-smallest-number-from-di-string
0
1
Observations:\n1. Maximum digit in the output is the len of the pattern + 1. E.g. if pattern is "D\' or "I" the max digit will be 2 (2**1** or 1**2**). For DD or II we\'ll have max digit 3 and etc.\n2. We can use counter as a pattern and reverse it each time we find \'I\'. E.g. If we have pattern "DDD I DDD I" the coun...
1
You are given a **0-indexed** string `pattern` of length `n` consisting of the characters `'I'` meaning **increasing** and `'D'` meaning **decreasing**. A **0-indexed** string `num` of length `n + 1` is created using the following conditions: * `num` consists of the digits `'1'` to `'9'`, where each digit is used *...
null
[Python3] greedy
construct-smallest-number-from-di-string
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/abc9891d642b2454c148af46a140ff3497f7ce3c) for solutions of weekly 306. \n\n```\nclass Solution:\n def smallestNumber(self, pattern: str) -> str:\n ans = [1]\n for ch in pattern: \n if ch == \'I\': \n m = a...
29
You are given a **0-indexed** string `pattern` of length `n` consisting of the characters `'I'` meaning **increasing** and `'D'` meaning **decreasing**. A **0-indexed** string `num` of length `n + 1` is created using the following conditions: * `num` consists of the digits `'1'` to `'9'`, where each digit is used *...
null
[Python] easy to understand greedy solution.
construct-smallest-number-from-di-string
0
1
This solution works by increasing the previous "I" by the total number of succeeding "D"s then decrementing 1 for every D. And then repeating the same process untill the loop ends. and check one last time out of the loop.\n```\nclass Solution:\n def smallestNumber(self, pattern: str) -> str:\n ans = []\n ...
5
You are given a **0-indexed** string `pattern` of length `n` consisting of the characters `'I'` meaning **increasing** and `'D'` meaning **decreasing**. A **0-indexed** string `num` of length `n + 1` is created using the following conditions: * `num` consists of the digits `'1'` to `'9'`, where each digit is used *...
null
Simple solution with using Stack DS
construct-smallest-number-from-di-string
0
1
# Intuition\nNote that problem can be solved by using `greedy`, `backtrack` or `stack` algorithm.\nFor this solution let me explain step-by-step `stack` - solution.\n\n\n---\n\nIf you haven\'t already familiar with [Stack DS](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)), than I **highly** recommend to know...
2
You are given a **0-indexed** string `pattern` of length `n` consisting of the characters `'I'` meaning **increasing** and `'D'` meaning **decreasing**. A **0-indexed** string `num` of length `n + 1` is created using the following conditions: * `num` consists of the digits `'1'` to `'9'`, where each digit is used *...
null
[Python3] dp
count-special-integers
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/abc9891d642b2454c148af46a140ff3497f7ce3c) for solutions of weekly 306. \n\n```\nclass Solution:\n def countSpecialNumbers(self, n: int) -> int:\n vals = list(map(int, str(n)))\n \n @cache\n def fn(i, m, on): \n ...
5
We call a positive integer **special** if all of its digits are **distinct**. Given a **positive** integer `n`, return _the number of special integers that belong to the interval_ `[1, n]`. **Example 1:** **Input:** n = 20 **Output:** 19 **Explanation:** All the integers from 1 to 20, except 11, are special. Thus, t...
null
Python (Simple Digit DP)
count-special-integers
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
We call a positive integer **special** if all of its digits are **distinct**. Given a **positive** integer `n`, return _the number of special integers that belong to the interval_ `[1, n]`. **Example 1:** **Input:** n = 20 **Output:** 19 **Explanation:** All the integers from 1 to 20, except 11, are special. Thus, t...
null
[Java/Python 3] Sliding Window T O(n) S O(1), w/ brief explanation and analysis.
minimum-recolors-to-get-k-consecutive-black-blocks
1
1
Maintain a sliding window of size `k`, keep updating the count of `W` out of it and find the minimum.\n\nNote: `lo` and `hi` are the lower and upper bounds of the sliding window, exclusive and inclusive respectively.\n```java\n public int minimumRecolors(String blocks, int k) {\n int min = Integer.MAX_VALUE;\...
25
You are given a **0-indexed** string `blocks` of length `n`, where `blocks[i]` is either `'W'` or `'B'`, representing the color of the `ith` block. The characters `'W'` and `'B'` denote the colors white and black, respectively. You are also given an integer `k`, which is the desired number of **consecutive** black blo...
null
Python Simple Solution
minimum-recolors-to-get-k-consecutive-black-blocks
0
1
# Intuition\nThink of slicing the string.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nReplace all \'W\' with \'B\' and append the count of \'W\' before replacing.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time...
1
You are given a **0-indexed** string `blocks` of length `n`, where `blocks[i]` is either `'W'` or `'B'`, representing the color of the `ith` block. The characters `'W'` and `'B'` denote the colors white and black, respectively. You are also given an integer `k`, which is the desired number of **consecutive** black blo...
null
[Python3] O(N) dp approach
time-needed-to-rearrange-a-binary-string
0
1
Please pull this git [commit](https://github.com/gaosanyong/leetcode/commit/e999ea07dc2ea2e8b7aad97696f67a3b965e496d) for solutions of biweekly 85. \n\n**Intuition**\nGiven the size of the problem, it is okay to run a simulation which takes `O(N^2)` to complete. However, a faster `O(N)` DP approach is available. \nHere...
53
You are given a binary string `s`. In one second, **all** occurrences of `"01 "` are **simultaneously** replaced with `"10 "`. This process **repeats** until no occurrences of `"01 "` exist. Return _the number of seconds needed to complete this process._ **Example 1:** **Input:** s = "0110101 " **Output:** 4 **Expl...
null
✅Python || Easy Approach || Replace (5 lines)
time-needed-to-rearrange-a-binary-string
0
1
```\nclass Solution:\n def secondsToRemoveOccurrences(self, s: str) -> int:\n\n ans = 0\n\n while \'01\' in s:\n ans += 1\n s = s.replace(\'01\', \'10\')\n \n return ans\n```
14
You are given a binary string `s`. In one second, **all** occurrences of `"01 "` are **simultaneously** replaced with `"10 "`. This process **repeats** until no occurrences of `"01 "` exist. Return _the number of seconds needed to complete this process._ **Example 1:** **Input:** s = "0110101 " **Output:** 4 **Expl...
null
Runtime 35ms, Memory 13.8mb Python Solution
time-needed-to-rearrange-a-binary-string
0
1
# Approach\n- The last "1" will take the longest time to travel to its destination in the string, which is the number of "0"s infront. \n- The special case is when "1" is right next to another "1", which will add one more step for the second 1 to move to the right.\n\n# Complexity\n- Time complexity: O(N)\n\n- Space co...
1
You are given a binary string `s`. In one second, **all** occurrences of `"01 "` are **simultaneously** replaced with `"10 "`. This process **repeats** until no occurrences of `"01 "` exist. Return _the number of seconds needed to complete this process._ **Example 1:** **Input:** s = "0110101 " **Output:** 4 **Expl...
null
Python3 easy with string replace
time-needed-to-rearrange-a-binary-string
0
1
\n\n# Code\n```\nclass Solution:\n def secondsToRemoveOccurrences(self, s: str) -> int:\n count = 0\n while "01" in s:\n s = s.replace("01", "10")\n count += 1\n return count\n\n \n```
1
You are given a binary string `s`. In one second, **all** occurrences of `"01 "` are **simultaneously** replaced with `"10 "`. This process **repeats** until no occurrences of `"01 "` exist. Return _the number of seconds needed to complete this process._ **Example 1:** **Input:** s = "0110101 " **Output:** 4 **Expl...
null
PYTHON | Beginner | Easy | 81% faster
time-needed-to-rearrange-a-binary-string
0
1
**Please upvode if it helps...**\n```\nclass Solution:\n def secondsToRemoveOccurrences(self, s: str) -> int:\n c=0\n for i in range(len(s)):\n if "01" in s:\n s=s.replace("01","10")\n c+=1\n return(c)\n\t\t```
1
You are given a binary string `s`. In one second, **all** occurrences of `"01 "` are **simultaneously** replaced with `"10 "`. This process **repeats** until no occurrences of `"01 "` exist. Return _the number of seconds needed to complete this process._ **Example 1:** **Input:** s = "0110101 " **Output:** 4 **Expl...
null
Python brute force step by step solution & small solution
time-needed-to-rearrange-a-binary-string
0
1
### **Brute Force Solution**\n\n```\nclass Solution:\n\tdef secondsToRemoveOccurrences(self, s: str) -> int:\n\t\tcount = 0\n\t\ttemp = ""\n\t\tones = s.count("1") # get the count of 1\n\t\tfor _ in range(ones):\n\t\t\t"""\n\t\t\tmake a string with total number of 1\n\t\t\t"""\n\t\t\ttemp += "1"\n\n\t\twhile s[:ones] !...
1
You are given a binary string `s`. In one second, **all** occurrences of `"01 "` are **simultaneously** replaced with `"10 "`. This process **repeats** until no occurrences of `"01 "` exist. Return _the number of seconds needed to complete this process._ **Example 1:** **Input:** s = "0110101 " **Output:** 4 **Expl...
null
[Python 3] Sweep Line - Difference Array
shifting-letters-ii
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
You are given a string `s` of lowercase English letters and a 2D integer array `shifts` where `shifts[i] = [starti, endi, directioni]`. For every `i`, **shift** the characters in `s` from the index `starti` to the index `endi` (**inclusive**) forward if `directioni = 1`, or shift the characters backward if `directioni ...
null
✅ Python Cumulative Sum || Easy Solution
shifting-letters-ii
0
1
In this problem, we should be doing the exact same thing as in the first part of this problem (shifting letters) but there is an extra complexity of finding the final changes for each of the letters. \n\nA brute force approach would be to iterate through all of the letters that need to be changed for each shift in arra...
20
You are given a string `s` of lowercase English letters and a 2D integer array `shifts` where `shifts[i] = [starti, endi, directioni]`. For every `i`, **shift** the characters in `s` from the index `starti` to the index `endi` (**inclusive**) forward if `directioni = 1`, or shift the characters backward if `directioni ...
null
[Python3] Line Sweep Method with Hashmap
shifting-letters-ii
0
1
Note that for one who doesn\'t know about line sweep technique, there will be a test case with enormous length giving TLE.\n\nFor knowing what character will become after shifting **n** position forward, we can use a list to achieve that purpose.\nAs there will be only lower letter, we can assign "a" ~ "z" to a list of...
1
You are given a string `s` of lowercase English letters and a 2D integer array `shifts` where `shifts[i] = [starti, endi, directioni]`. For every `i`, **shift** the characters in `s` from the index `starti` to the index `endi` (**inclusive**) forward if `directioni = 1`, or shift the characters backward if `directioni ...
null
2 Python Solutions with explanation[BruteForce + LineSweep]✔
shifting-letters-ii
0
1
\t**BRUTE-FORCE SOLUTION** (GIVING TLE)\n\tclass Solution:\n\t\tdef shiftingLetters(self, s: str, shifts: List[List[int]]) -> str:\n\t\t\ttoshift = defaultdict(int)\n\n\t\t\tfor i in shifts:\n\t\t\t\tif i[2] == 0:\n\t\t\t\t\tc = -1\n\t\t\t\telse:\n\t\t\t\t\tc = 1\n\t\t\t\tfor j in range(i[0], i[1] + 1):\n\t\t\t\t\ttosh...
1
You are given a string `s` of lowercase English letters and a 2D integer array `shifts` where `shifts[i] = [starti, endi, directioni]`. For every `i`, **shift** the characters in `s` from the index `starti` to the index `endi` (**inclusive**) forward if `directioni = 1`, or shift the characters backward if `directioni ...
null
Do it backwards O(N)
maximum-segment-sum-after-removals
0
1
For nums = [1,2,5,6,1], removeQueries = [0,3,2,4,1], the reverse process will be \nadd 1 : [0, 2, 0 ,0 ,0]\nadd 4 : [0, 2, 0 ,0 ,1]\nadd 2 : [0, 2, 5 ,0 ,1]\nadd 3 : [0, 2, 5, 6, 1]\nadd 0 : [1, 2, 5, 6, 1]\n\nWhen an index q is added, extend the contiguous sequence by finding if q+1 or q-1 exists, and also record the ...
40
You are given two **0-indexed** integer arrays `nums` and `removeQueries`, both of length `n`. For the `ith` query, the element in `nums` at the index `removeQueries[i]` is removed, splitting `nums` into different segments. A **segment** is a contiguous sequence of **positive** integers in `nums`. A **segment sum** is...
null
[Python3] Priority queue
maximum-segment-sum-after-removals
0
1
Please pull this git [commit](https://github.com/gaosanyong/leetcode/commit/e999ea07dc2ea2e8b7aad97696f67a3b965e496d) for solutions of biweekly 85. \n\n**Intuition**\nHere, I use \n1) a ordered set to store the points where `nums` are divided; \n2) a hash table mapping from left boundary to right boundary to validate i...
8
You are given two **0-indexed** integer arrays `nums` and `removeQueries`, both of length `n`. For the `ith` query, the element in `nums` at the index `removeQueries[i]` is removed, splitting `nums` into different segments. A **segment** is a contiguous sequence of **positive** integers in `nums`. A **segment sum** is...
null
[Python 3]Prefix Sum+Heap
maximum-segment-sum-after-removals
0
1
```\n \nclass Solution:\n def maximumSegmentSum(self, nums: List[int], removeQueries: List[int]) -> List[int]:\n n = len(nums)\n acc = [0]\n # prefix sum\n for num in nums:\n acc.append(acc[-1] + num)\n \n # current max sum with boundries\n q = [(-sum(nu...
1
You are given two **0-indexed** integer arrays `nums` and `removeQueries`, both of length `n`. For the `ith` query, the element in `nums` at the index `removeQueries[i]` is removed, splitting `nums` into different segments. A **segment** is a contiguous sequence of **positive** integers in `nums`. A **segment sum** is...
null
python 3 | union find
maximum-segment-sum-after-removals
0
1
```\nclass Solution:\n def maximumSegmentSum(self, nums: List[int], removeQueries: List[int]) -> List[int]:\n n = len(nums)\n res = [0] * n\n parent = [i for i in range(n)]\n rank = [0] * n\n sums = [0] * n\n \n def union(i, j):\n i, j = find(i), find(j)\n ...
1
You are given two **0-indexed** integer arrays `nums` and `removeQueries`, both of length `n`. For the `ith` query, the element in `nums` at the index `removeQueries[i]` is removed, splitting `nums` into different segments. A **segment** is a contiguous sequence of **positive** integers in `nums`. A **segment sum** is...
null
Python O(n) time complexity, easily understandable code
maximum-segment-sum-after-removals
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing the example of nums = [1,2,5,6,1], removeQueries = [0,3,2,4,1].\n\nStarting from the empty list [0,0,0,0,0], add elements to the list until you obtain the original list.\n\n1. [0,2,0,0,0]\n2. [0,2,0,0,1]\n3. [0,2,5,0,1]\n4. [0,2,5,6,1]\n5. [1,2,...
0
You are given two **0-indexed** integer arrays `nums` and `removeQueries`, both of length `n`. For the `ith` query, the element in `nums` at the index `removeQueries[i]` is removed, splitting `nums` into different segments. A **segment** is a contiguous sequence of **positive** integers in `nums`. A **segment sum** is...
null
Python Easy O(n)
minimum-hours-of-training-to-win-a-competition
0
1
\n# Code\n```\nclass Solution:\n def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:\n\n \n exdif = 0\n ensum = 0\n for i in range(len(energy)):\n\n if initialExperience <= experience[i]:\n exdi...
1
You are entering a competition, and are given two **positive** integers `initialEnergy` and `initialExperience` denoting your initial energy and initial experience respectively. You are also given two **0-indexed** integer arrays `energy` and `experience`, both of length `n`. You will face `n` opponents **in order**....
null
✅Python || Easy Approach
minimum-hours-of-training-to-win-a-competition
0
1
```\nclass Solution:\n def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:\n \n ans = 0\n n = len(energy)\n\n for i in range(n):\n while initialEnergy <= energy[i] or initialExperience <= experience[i]:\n ...
8
You are entering a competition, and are given two **positive** integers `initialEnergy` and `initialExperience` denoting your initial energy and initial experience respectively. You are also given two **0-indexed** integer arrays `energy` and `experience`, both of length `n`. You will face `n` opponents **in order**....
null
Build a Graph from the given tree, Use BFS to get the time to infect the nodes.
amount-of-time-for-binary-tree-to-be-infected
0
1
# Intuition\nsince we have to traverse back in the tree[top and bottom traversal]\nWe use Hashing. \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWe can make use of a hashmap where we make the children and parent mapping.\nUse BFS for traversing the node. Insert the currently visit...
1
You are given the `root` of a binary tree with **unique** values, and an integer `start`. At minute `0`, an **infection** starts from the node with value `start`. Each minute, a node becomes infected if: * The node is currently uninfected. * The node is adjacent to an infected node. Return _the number of minutes...
How can we find the brightness at every position on the street? We can use a hash table to store the change in brightness from the previous position to the current position.
Solution for Beginners : Amount of Time for Binary Tree to Be Infected (faster than 97% submission)
amount-of-time-for-binary-tree-to-be-infected
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. -->\nVery similar to the question https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/\nFirst Solve the previous question and then come to this.\nSteps are ex...
0
You are given the `root` of a binary tree with **unique** values, and an integer `start`. At minute `0`, an **infection** starts from the node with value `start`. Each minute, a node becomes infected if: * The node is currently uninfected. * The node is adjacent to an infected node. Return _the number of minutes...
How can we find the brightness at every position on the street? We can use a hash table to store the change in brightness from the previous position to the current position.
[Python3] bfs
amount-of-time-for-binary-tree-to-be-infected
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/b7391a11acc4e9dbe563ebef84f8d78f7943a0f7) for solutions of weekly 307. \n\n**Intuition**\nI find it easier to treat the tree as a graph. First, I convert the tree to graph. Then I run a BFS to find the furthest away point which represents the answe...
39
You are given the `root` of a binary tree with **unique** values, and an integer `start`. At minute `0`, an **infection** starts from the node with value `start`. Each minute, a node becomes infected if: * The node is currently uninfected. * The node is adjacent to an infected node. Return _the number of minutes...
How can we find the brightness at every position on the street? We can use a hash table to store the change in brightness from the previous position to the current position.
Python DFS Soln | Faster than 90% w/ Proof | Easy to Understand
amount-of-time-for-binary-tree-to-be-infected
0
1
Idea is that we can mutate the given tree node to hold parent pointers.\n1. Add parent pointer to all the nodes\n2. Calculate max depth from the start node\n```\ndef amountOfTime(self, root: Optional[TreeNode], start: int) -> int:\n\t# DFS function to add parent pointer to all nodes and get the start node\n\tdef addPar...
1
You are given the `root` of a binary tree with **unique** values, and an integer `start`. At minute `0`, an **infection** starts from the node with value `start`. Each minute, a node becomes infected if: * The node is currently uninfected. * The node is adjacent to an infected node. Return _the number of minutes...
How can we find the brightness at every position on the street? We can use a hash table to store the change in brightness from the previous position to the current position.
Python3 || Recursive || Simple
amount-of-time-for-binary-tree-to-be-infected
0
1
```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\nclass Solution:\n\n graph = []\n\n def init_graph(self, node):\n if node.left:\n self.graph[node.val].ap...
2
You are given the `root` of a binary tree with **unique** values, and an integer `start`. At minute `0`, an **infection** starts from the node with value `start`. Each minute, a node becomes infected if: * The node is currently uninfected. * The node is adjacent to an infected node. Return _the number of minutes...
How can we find the brightness at every position on the street? We can use a hash table to store the change in brightness from the previous position to the current position.
[Python3] Heap/Priority Queue, O(NlogN + klogk)
find-the-k-sum-of-an-array
0
1
**Initial Observation**\n1. Given `n` can be as large as `10^5`, the time complexity of this problem has to be no worse than log-linear.\n2. This problem is dealing with *subsequences* but not *subarrays*, indicating we can shuffle the order of the original array, e.g. by sorting it.\n3. Given `-10^9 <= nums[i] <= 10^9...
91
You are given an integer array `nums` and a **positive** integer `k`. You can choose any **subsequence** of the array and sum all of its elements together. We define the **K-Sum** of the array as the `kth` **largest** subsequence sum that can be obtained (**not** necessarily distinct). Return _the K-Sum of the array_...
null
[Python3] priority queue
find-the-k-sum-of-an-array
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/b7391a11acc4e9dbe563ebef84f8d78f7943a0f7) for solutions of weekly 307. \n\n**Intuition**\nHere, I will discuss a strategy to find the kth largest subsequence sum. \n* We start from the sum of all positive numbers in `nums` which is the largest one ...
45
You are given an integer array `nums` and a **positive** integer `k`. You can choose any **subsequence** of the array and sum all of its elements together. We define the **K-Sum** of the array as the `kth` **largest** subsequence sum that can be obtained (**not** necessarily distinct). Return _the K-Sum of the array_...
null
Clear Py3 solution
find-the-k-sum-of-an-array
0
1
# Code\n```\nfrom sortedcontainers import SortedList\n\nclass Solution:\n def kSum(self, nums: List[int], k: int) -> int:\n ps = sum([x for x in nums if x >= 0])\n al = sorted([x if x >= 0 else -x for x in nums])\n # print(al)\n q = SortedList()\n q.add((ps, 0))\n \n ...
0
You are given an integer array `nums` and a **positive** integer `k`. You can choose any **subsequence** of the array and sum all of its elements together. We define the **K-Sum** of the array as the `kth` **largest** subsequence sum that can be obtained (**not** necessarily distinct). Return _the K-Sum of the array_...
null
FSM + full binary tree + SortedList
find-the-k-sum-of-an-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given an integer array `nums` and a **positive** integer `k`. You can choose any **subsequence** of the array and sum all of its elements together. We define the **K-Sum** of the array as the `kth` **largest** subsequence sum that can be obtained (**not** necessarily distinct). Return _the K-Sum of the array_...
null
[Python] Straight forward solution; Explained
longest-subsequence-with-limited-sum
0
1
**Three steps**. See the details in the comments.\n\n```\nclass Solution:\n def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:\n # step 1: sort the nums, O(logn)\n nums.sort()\n # step 2: calculate the running sum of the nums, O(n)\n self.running_sum = []\n ...
1
You are given an integer array `nums` of length `n`, and an integer array `queries` of length `m`. Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the **maximum** size of a **subsequence** that you can take from_ `nums` _such that the **sum** of its elements is less than or equal to_ `queries[i]`. ...
null
[Python3] 2-line binary search
longest-subsequence-with-limited-sum
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/ea6bc01b091cbf032b9c7ac2d3c09cb4f5cd0d2d) for solutions of weekly 308. \n\n**Intuition**\nFor each query, we always try to use the smallest number availabel for the summation, which results in below binary search implementation. \n\n**Analysis**\nT...
9
You are given an integer array `nums` of length `n`, and an integer array `queries` of length `m`. Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the **maximum** size of a **subsequence** that you can take from_ `nums` _such that the **sum** of its elements is less than or equal to_ `queries[i]`. ...
null
Prefix Sum
longest-subsequence-with-limited-sum
1
1
The minimal sum of any `k` elements of the array is the sum of `k` smallest elements.\n\nSo, we sort the array first. Then, we apply prefix sum so that the array `i`-th element of the array contains the minimal sum of `i` elements.\n\nFinally, we use a binary search to find the maximum number of elements for each query...
21
You are given an integer array `nums` of length `n`, and an integer array `queries` of length `m`. Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the **maximum** size of a **subsequence** that you can take from_ `nums` _such that the **sum** of its elements is less than or equal to_ `queries[i]`. ...
null
✅Python || 2 Easy Approaches || Prefix Sum
longest-subsequence-with-limited-sum
0
1
```\nclass Solution:\n def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:\n \n numsSorted = sorted(nums)\n res = []\n\t\t\n for q in queries:\n total = 0\n count = 0\n for num in numsSorted:\n total += num\n ...
2
You are given an integer array `nums` of length `n`, and an integer array `queries` of length `m`. Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the **maximum** size of a **subsequence** that you can take from_ `nums` _such that the **sum** of its elements is less than or equal to_ `queries[i]`. ...
null
✅ Python Solution | Easy Approach
longest-subsequence-with-limited-sum
0
1
```\nclass Solution:\n def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:\n answer = [0] * len(queries)\n for id, query in enumerate(queries):\n spec_sum = 0\n for i, number in enumerate(sorted(nums)):\n spec_sum += number\n\n ...
2
You are given an integer array `nums` of length `n`, and an integer array `queries` of length `m`. Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the **maximum** size of a **subsequence** that you can take from_ `nums` _such that the **sum** of its elements is less than or equal to_ `queries[i]`. ...
null
[Java/Python 3] Sort and Binary Search, w/ brief explanation and analysis.
longest-subsequence-with-limited-sum
1
1
Try to use small numbers in subsequence so that we can make it as long as possible. Therefore, it is logical to sort the input array and then use prefix sum array to binary search to locate the longest size.\n\n```java\n public int[] answerQueries(int[] nums, int[] queries) {\n int m = queries.length, n = num...
14
You are given an integer array `nums` of length `n`, and an integer array `queries` of length `m`. Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the **maximum** size of a **subsequence** that you can take from_ `nums` _such that the **sum** of its elements is less than or equal to_ `queries[i]`. ...
null
Python 1-liner functional programming. O((m + n) * log(n)), beats 97.88% runtime.
longest-subsequence-with-limited-sum
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n- Sort `nums`\n- Calculate `prefix_sums`.\n- Binary search the `prefix_sums` for every `query`.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O((n + m)*log(n))$$\n\n- Space complexity:\n<!-- Add your spa...
1
You are given an integer array `nums` of length `n`, and an integer array `queries` of length `m`. Return _an array_ `answer` _of length_ `m` _where_ `answer[i]` _is the **maximum** size of a **subsequence** that you can take from_ `nums` _such that the **sum** of its elements is less than or equal to_ `queries[i]`. ...
null
✅[Python3//C++//Java]✅ Easy and understand (Stack Simulation)
removing-stars-from-a-string
1
1
This code defines a function removeStars that takes a string s as input and returns a modified version of the input string with all asterisks (*) removed along with the preceding character.\n\nHere is a step-by-step explanation of the code:\n1. Initialize an empty list ans that will be used to build the modified string...
266
You are given a string `s`, which contains stars `*`. In one operation, you can: * Choose a star in `s`. * Remove the closest **non-star** character to its **left**, as well as remove the star itself. Return _the string after **all** stars have been removed_. **Note:** * The input will be generated such that...
null
Beginner Friendly || Full explained || [Java/C++/Python]
removing-stars-from-a-string
1
1
# Intuition\n1. Use a stack to store the characters. Pop one character off the stack at each star. Otherwise, we push the character onto the stack\n\n# Approach\n1. **Base Case Check:**\n - If the input string is empty or null, the method returns an empty string.\n2. **Stack Initialization:**\n - A stack is initi...
1
You are given a string `s`, which contains stars `*`. In one operation, you can: * Choose a star in `s`. * Remove the closest **non-star** character to its **left**, as well as remove the star itself. Return _the string after **all** stars have been removed_. **Note:** * The input will be generated such that...
null
Python!! Python3 Understandable and simplest solution.
removing-stars-from-a-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given a string `s`, which contains stars `*`. In one operation, you can: * Choose a star in `s`. * Remove the closest **non-star** character to its **left**, as well as remove the star itself. Return _the string after **all** stars have been removed_. **Note:** * The input will be generated such that...
null
🐍✅ Python3 easiest solution 🔥🔥
removing-stars-from-a-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Using Stack**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- push in stack till not found **\'*\'**\n- when found **"*"** this symbol pop from stack.\n- do this till end of s.\n- return stack in form of strin...
1
You are given a string `s`, which contains stars `*`. In one operation, you can: * Choose a star in `s`. * Remove the closest **non-star** character to its **left**, as well as remove the star itself. Return _the string after **all** stars have been removed_. **Note:** * The input will be generated such that...
null
Stack.py
removing-stars-from-a-string
0
1
# Code\n```\nclass Solution:\n def removeStars(self, s: str) -> str:\n l=[]\n for i in s:\n if i==\'*\':l.pop()\n else:l.append(i)\n return "".join(l)\n \n\n```
1
You are given a string `s`, which contains stars `*`. In one operation, you can: * Choose a star in `s`. * Remove the closest **non-star** character to its **left**, as well as remove the star itself. Return _the string after **all** stars have been removed_. **Note:** * The input will be generated such that...
null
Python easy solution using stack
removing-stars-from-a-string
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nCreating Stack to maintain the characters of string. if any `*` is found we pop the previous character in stack.\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...
1
You are given a string `s`, which contains stars `*`. In one operation, you can: * Choose a star in `s`. * Remove the closest **non-star** character to its **left**, as well as remove the star itself. Return _the string after **all** stars have been removed_. **Note:** * The input will be generated such that...
null
C++/Python loop & accumulate||94ms Beats 100%
minimum-amount-of-time-to-collect-garbage
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n```\ntotal time=time for collecting garbage + time for traveling\n```\nDivide the questions into 2 parts; it might make the solution easier.\ntime for collecting garbage is very easy; other is also not difficult.\n# Approach\n<!-- Describ...
17
You are given a **0-indexed** array of strings `garbage` where `garbage[i]` represents the assortment of garbage at the `ith` house. `garbage[i]` consists only of the characters `'M'`, `'P'` and `'G'` representing one unit of metal, paper and glass garbage respectively. Picking up **one** unit of any type of garbage ta...
null
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥
minimum-amount-of-time-to-collect-garbage
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(HashMaps)***\n1. **Prefix Sum Calculation:**\n\n - `prefixSum` vector stores the prefix sum of the `travel` vector.\n - It helps in calculating the distance traveled up to a certain point efficiently.\n1....
4
You are given a **0-indexed** array of strings `garbage` where `garbage[i]` represents the assortment of garbage at the `ith` house. `garbage[i]` consists only of the characters `'M'`, `'P'` and `'G'` representing one unit of metal, paper and glass garbage respectively. Picking up **one** unit of any type of garbage ta...
null
【Video】Give me 10 minutes - Beats 98% - How we think about a solution
minimum-amount-of-time-to-collect-garbage
1
1
# Intuition\nIterate through from the last index.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/GZWR5cWZ3pw\n\n\u25A0 Timeline\n`0:05` Talk about time to pick up all garbages \n`1:44` Talk about time to travel to the next house\n`5:37` Demonstrate how it works\n`8:00` Coding\n`11:12` Time Complexity and Space Complexi...
48
You are given a **0-indexed** array of strings `garbage` where `garbage[i]` represents the assortment of garbage at the `ith` house. `garbage[i]` consists only of the characters `'M'`, `'P'` and `'G'` representing one unit of metal, paper and glass garbage respectively. Picking up **one** unit of any type of garbage ta...
null
Easy Intuitive solution using Hashmap and Prefix Sum
minimum-amount-of-time-to-collect-garbage
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. -->\ntravel time(taking prefix sum) will give us the time to travel to the particular index and travel_time[last_index[i] - 1] will give us the time to travel to the last i...
2
You are given a **0-indexed** array of strings `garbage` where `garbage[i]` represents the assortment of garbage at the `ith` house. `garbage[i]` consists only of the characters `'M'`, `'P'` and `'G'` representing one unit of metal, paper and glass garbage respectively. Picking up **one** unit of any type of garbage ta...
null
✅ 100% || 🚀 Greedy Approach ||
minimum-amount-of-time-to-collect-garbage
1
1
\n\n# C++ Result:\n![Screenshot 2023-11-20 at 5.50.53\u202FAM.png](https://assets.leetcode.com/users/images/c0d70d54-531f-438f-b623-70d26a06202e_1700439683.2697353.png)\n\n# Python Result:\n![Screenshot 2023-11-20 at 5.51.42\u202FAM.png](https://assets.leetcode.com/users/images/5a0b91fd-29b8-4a69-94fb-6ef9b9947859_1700...
2
You are given a **0-indexed** array of strings `garbage` where `garbage[i]` represents the assortment of garbage at the `ith` house. `garbage[i]` consists only of the characters `'M'`, `'P'` and `'G'` representing one unit of metal, paper and glass garbage respectively. Picking up **one** unit of any type of garbage ta...
null
[Python3] Greedy + prefix sum || beats 100%
minimum-amount-of-time-to-collect-garbage
0
1
# Intuition\n- Find last position (the most right house) for each type of garbage.\n- Find distance for every house using prefix sum (use [`itertools.accumulate`](https://docs.python.org/3/library/itertools.html#itertools.accumulate) to simplify code).\n- Don\'t forget to count the garbage (1 sek to peek 1 unit of any ...
8
You are given a **0-indexed** array of strings `garbage` where `garbage[i]` represents the assortment of garbage at the `ith` house. `garbage[i]` consists only of the characters `'M'`, `'P'` and `'G'` representing one unit of metal, paper and glass garbage respectively. Picking up **one** unit of any type of garbage ta...
null
✅Python || Beats 100% || O(n)
minimum-amount-of-time-to-collect-garbage
0
1
![Screenshot 2023-11-20 194617.png](https://assets.leetcode.com/users/images/d66ea612-fa5d-42a5-adf6-2db785cf6dd6_1700491643.967531.png)\n\n# Problem\nThe problem is asking to minimize the time taken to collect all the garbage. We have three types of garbage and three trucks, each responsible for one type of garbage. T...
1
You are given a **0-indexed** array of strings `garbage` where `garbage[i]` represents the assortment of garbage at the `ith` house. `garbage[i]` consists only of the characters `'M'`, `'P'` and `'G'` representing one unit of metal, paper and glass garbage respectively. Picking up **one** unit of any type of garbage ta...
null
Easy python solution with comments! Time complexity O(n*m)
minimum-amount-of-time-to-collect-garbage
0
1
# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n*m): where n is no of houses to visit, m is the max length of garbage to collect at any house in our array.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n): dominated by space complexity of c...
1
You are given a **0-indexed** array of strings `garbage` where `garbage[i]` represents the assortment of garbage at the `ith` house. `garbage[i]` consists only of the characters `'M'`, `'P'` and `'G'` representing one unit of metal, paper and glass garbage respectively. Picking up **one** unit of any type of garbage ta...
null
Easy Python Solution || Beats 94% in Runtime
minimum-amount-of-time-to-collect-garbage
0
1
![image.png](https://assets.leetcode.com/users/images/1bc23daa-4b60-4c7d-8c40-9bb8312ad521_1700452494.021158.png)\n\n# Approach\n1. Keep track of index of the last occurance of each garbage.\n2. Also keep track of frequency of Each letter. (You can maintain a single variable which stores total freq of each letter, here...
1
You are given a **0-indexed** array of strings `garbage` where `garbage[i]` represents the assortment of garbage at the `ith` house. `garbage[i]` consists only of the characters `'M'`, `'P'` and `'G'` representing one unit of metal, paper and glass garbage respectively. Picking up **one** unit of any type of garbage ta...
null
🚀 Easy Iterative Approach || Explained Intuition🚀
minimum-amount-of-time-to-collect-garbage
1
1
# Problem Description\n\nGiven an array `garbage` representing the types of garbage at each house (`M` for metal, `P` for paper, `G` for glass), and an array `travel` representing the travel time between consecutive houses, **determine** the **minimum** number of minutes needed for three garbage trucks to pick up all t...
39
You are given a **0-indexed** array of strings `garbage` where `garbage[i]` represents the assortment of garbage at the `ith` house. `garbage[i]` consists only of the characters `'M'`, `'P'` and `'G'` representing one unit of metal, paper and glass garbage respectively. Picking up **one** unit of any type of garbage ta...
null
✅✅✅ Best-Optimized Solution 🌟Simple with Observation 💡🎯🏆
minimum-amount-of-time-to-collect-garbage
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe key insight here is that for each type of garbage (\'G\', \'P\', \'M\'), we want to find the last occurrence in the sequence of houses. This is because once a garbage truck picks up a particular type of garbage, it doesn\'t need to tr...
1
You are given a **0-indexed** array of strings `garbage` where `garbage[i]` represents the assortment of garbage at the `ith` house. `garbage[i]` consists only of the characters `'M'`, `'P'` and `'G'` representing one unit of metal, paper and glass garbage respectively. Picking up **one** unit of any type of garbage ta...
null
Reverse Loop With Prefix Sum Frequency Transform | Commented and Explained | 100% T and S
minimum-amount-of-time-to-collect-garbage
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA backwards loop can find the last index of each type of garbage \nA prefix sum of times can find the cost of the traversals needed \nA hashmap of the last indices then allows us to find the costs up to a specific point -> aka prefix sum ...
1
You are given a **0-indexed** array of strings `garbage` where `garbage[i]` represents the assortment of garbage at the `ith` house. `garbage[i]` consists only of the characters `'M'`, `'P'` and `'G'` representing one unit of metal, paper and glass garbage respectively. Picking up **one** unit of any type of garbage ta...
null
PYTHON3 FOR BEGINNERS || VERY EASY TO UNDERSTAND || BEST EFFICIENT
minimum-amount-of-time-to-collect-garbage
0
1
# Intuition\n**1)Cumulative Distance Calculation:**\n\nThe post list is used to store the cumulative sum of travel distances at each position. This is helpful for quickly determining the total distance traveled up to a certain point.\n\n**2)Iterating Backwards through Garbage Positions:**\n\nThe code iterates backward ...
1
You are given a **0-indexed** array of strings `garbage` where `garbage[i]` represents the assortment of garbage at the `ith` house. `garbage[i]` consists only of the characters `'M'`, `'P'` and `'G'` representing one unit of metal, paper and glass garbage respectively. Picking up **one** unit of any type of garbage ta...
null
Python Easy & Brute force Solution
minimum-amount-of-time-to-collect-garbage
0
1
# Approach\nBrute force\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n\n# Code\n```\nclass Solution:\n def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n join_garbage = "".join(garbage)\n count = 0\n for i in join_garbage:\n if i =...
1
You are given a **0-indexed** array of strings `garbage` where `garbage[i]` represents the assortment of garbage at the `ith` house. `garbage[i]` consists only of the characters `'M'`, `'P'` and `'G'` representing one unit of metal, paper and glass garbage respectively. Picking up **one** unit of any type of garbage ta...
null
Simple solution with Prefix Sum in Python3
minimum-amount-of-time-to-collect-garbage
0
1
# Intuition\nHere we have:\n- `garbage`, that denotes to garbage for a particular home (G, P, M for glass, plastic and metal respectively)\n- `travel` as time to travel between homes\n- our goal is to define **how much** time trucks need to spend to collect all of the `garbage` **optimally**\n\nEach garbage collection ...
1
You are given a **0-indexed** array of strings `garbage` where `garbage[i]` represents the assortment of garbage at the `ith` house. `garbage[i]` consists only of the characters `'M'`, `'P'` and `'G'` representing one unit of metal, paper and glass garbage respectively. Picking up **one** unit of any type of garbage ta...
null
[Python 3] Topological Sorting
build-a-matrix-with-conditions
0
1
\n\n\n```\n\ndef buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]:\n ans = [[0] * k for _ in range(k)]\n\t\t\n def topological(condition):\n graph = defaultdict(list)\n indegree = [0] * k\n for a, b in condition:\...
1
You are given a **positive** integer `k`. You are also given: * a 2D integer array `rowConditions` of size `n` where `rowConditions[i] = [abovei, belowi]`, and * a 2D integer array `colConditions` of size `m` where `colConditions[i] = [lefti, righti]`. The two arrays contain integers from `1` to `k`. You have to...
null
[Python3] Topological Sort - Simple Solution
build-a-matrix-with-conditions
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nFind the order for row and col respectively and then assign them to the matrix. Note that there are only `k` number need to assign which is also the side of square matrix. Thus we can assign each number in each unique row an...
2
You are given a **positive** integer `k`. You are also given: * a 2D integer array `rowConditions` of size `n` where `rowConditions[i] = [abovei, belowi]`, and * a 2D integer array `colConditions` of size `m` where `colConditions[i] = [lefti, righti]`. The two arrays contain integers from `1` to `k`. You have to...
null
Topo_sort || python
build-a-matrix-with-conditions
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1)concept is to find topo_sort for row and col...\n2)iterate from topo_sort of row elements and find its corresponding pos in topo_sort of col\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time ...
1
You are given a **positive** integer `k`. You are also given: * a 2D integer array `rowConditions` of size `n` where `rowConditions[i] = [abovei, belowi]`, and * a 2D integer array `colConditions` of size `m` where `colConditions[i] = [lefti, righti]`. The two arrays contain integers from `1` to `k`. You have to...
null
[Python3] topological sort
build-a-matrix-with-conditions
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/ea6bc01b091cbf032b9c7ac2d3c09cb4f5cd0d2d) for solutions of weekly 308. \n\n**Intuition**\nThe workhorse of this problem is topological sort. The orders in `aboveConditions` and `leftConditions` construct two graphs. Via topological sort, the order ...
15
You are given a **positive** integer `k`. You are also given: * a 2D integer array `rowConditions` of size `n` where `rowConditions[i] = [abovei, belowi]`, and * a 2D integer array `colConditions` of size `m` where `colConditions[i] = [lefti, righti]`. The two arrays contain integers from `1` to `k`. You have to...
null
[Python 3] Topological Sort Ez To Understand
build-a-matrix-with-conditions
0
1
Intuition: For each row/col conditions, consider them as a directed edge. For example, in the given test case: ![image](https://assets.leetcode.com/users/images/02b8630c-10ae-416a-9240-64d30480a966_1661670161.2752652.png)\n\nrow_conditions could be represented as two edges: 1 -> 2 and 3 -> 2. This could work because th...
1
You are given a **positive** integer `k`. You are also given: * a 2D integer array `rowConditions` of size `n` where `rowConditions[i] = [abovei, belowi]`, and * a 2D integer array `colConditions` of size `m` where `colConditions[i] = [lefti, righti]`. The two arrays contain integers from `1` to `k`. You have to...
null
3 Lines of Code
find-subarrays-with-equal-sum
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 **0-indexed** integer array `nums`, determine whether there exist **two** subarrays of length `2` with **equal** sum. Note that the two subarrays must begin at **different** indices. Return `true` _if these subarrays exist, and_ `false` _otherwise._ A **subarray** is a contiguous non-empty sequence of element...
null
beginner friendly code in python.
find-subarrays-with-equal-sum
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 **0-indexed** integer array `nums`, determine whether there exist **two** subarrays of length `2` with **equal** sum. Note that the two subarrays must begin at **different** indices. Return `true` _if these subarrays exist, and_ `false` _otherwise._ A **subarray** is a contiguous non-empty sequence of element...
null
Python3 || 3 (or 1) lines, T/M: 36ms/13.9MB
find-subarrays-with-equal-sum
0
1
```\nclass Solution: # Let nums = [ 1,3,2,4,1,4],\n \n # Here\'s the plan: \n # 1) Compute all the sums: ((1,3),(3,2),(4,1),(1,4))\n # -->(1,5,5,5)\n # 2) Determine whether any sum occurs twi...
4
Given a **0-indexed** integer array `nums`, determine whether there exist **two** subarrays of length `2` with **equal** sum. Note that the two subarrays must begin at **different** indices. Return `true` _if these subarrays exist, and_ `false` _otherwise._ A **subarray** is a contiguous non-empty sequence of element...
null
Python || Sliding window || Bruteforce
find-subarrays-with-equal-sum
0
1
# Bruteforce \n# Sliding window\n## Time -> O(n)\n## Space -> O(n)\n\n```\nclass Solution:\n def findSubarrays(self, nums: List[int]) -> bool:\n """ \n\tBruteforce approch\n\t"""\n# for i in range(len(nums)-2):\n# summ1 = nums[i] + nums[i+1]\n# # for j in range(i+1,len(nums)):\n# ...
4
Given a **0-indexed** integer array `nums`, determine whether there exist **two** subarrays of length `2` with **equal** sum. Note that the two subarrays must begin at **different** indices. Return `true` _if these subarrays exist, and_ `false` _otherwise._ A **subarray** is a contiguous non-empty sequence of element...
null
Python | Easy Understanding
find-subarrays-with-equal-sum
0
1
```\nclass Solution:\n def findSubarrays(self, nums: List[int]) -> bool:\n all_sums = []\n for i in range(0, len(nums) - 1):\n if nums[i] + nums[i + 1] in all_sums:\n return True\n else:\n all_sums.append(nums[i] + nums[i + 1])\n \n return F...
2
Given a **0-indexed** integer array `nums`, determine whether there exist **two** subarrays of length `2` with **equal** sum. Note that the two subarrays must begin at **different** indices. Return `true` _if these subarrays exist, and_ `false` _otherwise._ A **subarray** is a contiguous non-empty sequence of element...
null
Optimum solution using python easy to understand.
find-subarrays-with-equal-sum
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
3
Given a **0-indexed** integer array `nums`, determine whether there exist **two** subarrays of length `2` with **equal** sum. Note that the two subarrays must begin at **different** indices. Return `true` _if these subarrays exist, and_ `false` _otherwise._ A **subarray** is a contiguous non-empty sequence of element...
null
✅ Python 99% Easy Simple Solution | Set
find-subarrays-with-equal-sum
0
1
#### Easy Solution:\n* Sum the two indexes `getSum`\n* If the `getSum` is in `sums` array then return true\n* Else add the summation into the array\n* After iterate through the array return false as there is no similar sum\n```\nclass Solution:\n\tdef findSubarrays(self, nums: list[int]) -> bool:\n\t\tsums = set()\n\n\...
1
Given a **0-indexed** integer array `nums`, determine whether there exist **two** subarrays of length `2` with **equal** sum. Note that the two subarrays must begin at **different** indices. Return `true` _if these subarrays exist, and_ `false` _otherwise._ A **subarray** is a contiguous non-empty sequence of element...
null
simple solution
strictly-palindromic-number
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
An integer `n` is **strictly palindromic** if, for **every** base `b` between `2` and `n - 2` (**inclusive**), the string representation of the integer `n` in base `b` is **palindromic**. Given an integer `n`, return `true` _if_ `n` _is **strictly palindromic** and_ `false` _otherwise_. A string is **palindromic** if...
null
3 SECONDS ❌ EASY TO UNDERSTAND ❌ IMPORTANT VARIABLE ❌ BEATS SOME USERS ❌ HASHMAP ❌ GREEDY ALGORITHM
strictly-palindromic-number
0
1
# Intuition\nimplement hasmap\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: 3 seconds\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: \uD83E\uDD37\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solu...
1
An integer `n` is **strictly palindromic** if, for **every** base `b` between `2` and `n - 2` (**inclusive**), the string representation of the integer `n` in base `b` is **palindromic**. Given an integer `n`, return `true` _if_ `n` _is **strictly palindromic** and_ `false` _otherwise_. A string is **palindromic** if...
null
professional cheater | python
strictly-palindromic-number
0
1
\n# Code\n```\nclass Solution:\n def isStrictlyPalindromic(self, n: int) -> bool:\n return False\n```
0
An integer `n` is **strictly palindromic** if, for **every** base `b` between `2` and `n - 2` (**inclusive**), the string representation of the integer `n` in base `b` is **palindromic**. Given an integer `n`, return `true` _if_ `n` _is **strictly palindromic** and_ `false` _otherwise_. A string is **palindromic** if...
null
✔ Simple Python Code || Easily Understandable
strictly-palindromic-number
0
1
\n\n# Approach\n- Starting from ```base 2 to n```, find out the binary representation\n- Check for palindrom and count total no of palindroms\n- Check total no of palindroms ```if count == n-2:``` and if \u2714 return true\n- ```n-2``` is to exclude ```0,1``` as we\'r checking the base from 2\n\n\n# Code\n```\nclass So...
3
An integer `n` is **strictly palindromic** if, for **every** base `b` between `2` and `n - 2` (**inclusive**), the string representation of the integer `n` in base `b` is **palindromic**. Given an integer `n`, return `true` _if_ `n` _is **strictly palindromic** and_ `false` _otherwise_. A string is **palindromic** if...
null
Easy Python Solution
strictly-palindromic-number
0
1
\n# Code\n```\nclass Solution:\n def isStrictlyPalindromic(self, n: int) -> bool:\n for i in range(2,n-1):\n s=self.convert(n,i)\n if str(s)!=str(s)[::-1]:\n return False\n return True\n\n def convert(self, n,x):\n tem=""\n while n>0:\n t...
2
An integer `n` is **strictly palindromic** if, for **every** base `b` between `2` and `n - 2` (**inclusive**), the string representation of the integer `n` in base `b` is **palindromic**. Given an integer `n`, return `true` _if_ `n` _is **strictly palindromic** and_ `false` _otherwise_. A string is **palindromic** if...
null
Python solution
strictly-palindromic-number
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
An integer `n` is **strictly palindromic** if, for **every** base `b` between `2` and `n - 2` (**inclusive**), the string representation of the integer `n` in base `b` is **palindromic**. Given an integer `n`, return `true` _if_ `n` _is **strictly palindromic** and_ `false` _otherwise_. A string is **palindromic** if...
null
One Liner code that will beat 90%
strictly-palindromic-number
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
An integer `n` is **strictly palindromic** if, for **every** base `b` between `2` and `n - 2` (**inclusive**), the string representation of the integer `n` in base `b` is **palindromic**. Given an integer `n`, return `true` _if_ `n` _is **strictly palindromic** and_ `false` _otherwise_. A string is **palindromic** if...
null
One Word Solution | Python
strictly-palindromic-number
0
1
```\nclass Solution:\n def isStrictlyPalindromic(self, n: int) -> bool:\n pass\n```
1
An integer `n` is **strictly palindromic** if, for **every** base `b` between `2` and `n - 2` (**inclusive**), the string representation of the integer `n` in base `b` is **palindromic**. Given an integer `n`, return `true` _if_ `n` _is **strictly palindromic** and_ `false` _otherwise_. A string is **palindromic** if...
null