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 one liner with explanation
a-number-after-a-double-reversal
0
1
False is when 2+ digit numbers have trailing zeroes, otherwise every other double reversal condition is True\n\n\n```\nclass Solution:\n def isSameAfterReversals(self, num: int) -> bool:\n return [False if len(str(num)) > 1 and str(num)[-1] == "0" else True][0]\n```
0
**Reversing** an integer means to reverse all its digits. * For example, reversing `2021` gives `1202`. Reversing `12300` gives `321` as the **leading zeros are not retained**. Given an integer `num`, **reverse** `num` to get `reversed1`, **then reverse** `reversed1` to get `reversed2`. Return `true` _if_ `reversed...
Sort the array. For every index do a binary search to get the possible right end of the window and calculate the possible answer.
[Python3] Clean Solution
execution-of-all-suffix-instructions-staying-in-a-grid
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 an `n x n` grid, with the top-left cell at `(0, 0)` and the bottom-right cell at `(n - 1, n - 1)`. You are given the integer `n` and an integer array `startPos` where `startPos = [startrow, startcol]` indicates that a robot is initially at cell `(startrow, startcol)`. You are also given a **0-indexed** string...
null
[Python] Straight-forward O(n ^ 2) solution (still fast - 85%)
execution-of-all-suffix-instructions-staying-in-a-grid
0
1
# Complexity\n- Time complexity:\nO(N ^ 2)\n- Space complexity:\nO(N)\n\n# Code\n```python []\nclass Solution:\n def executeInstructions(self, n: int, startPos: list[int], s: str) -> list[int]:\n\n def num_of_valid_instructions(s, pos, start, end):\n row, colon = pos\n k = 0\n ...
3
There is an `n x n` grid, with the top-left cell at `(0, 0)` and the bottom-right cell at `(n - 1, n - 1)`. You are given the integer `n` and an integer array `startPos` where `startPos = [startrow, startcol]` indicates that a robot is initially at cell `(startrow, startcol)`. You are also given a **0-indexed** string...
null
Python3 O(N ^ 2) solution with simulation (92.80% Runtime)
execution-of-all-suffix-instructions-staying-in-a-grid
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n![image.png](https://assets.leetcode.com/users/images/cee5ce8d-f90f-434d-b929-81459715328f_1702043613.5384393.png)\nIteratively check for out of bounds while updating counts\n\n# Approach\n<!-- Describe your approach to solving the proble...
0
There is an `n x n` grid, with the top-left cell at `(0, 0)` and the bottom-right cell at `(n - 1, n - 1)`. You are given the integer `n` and an integer array `startPos` where `startPos = [startrow, startcol]` indicates that a robot is initially at cell `(startrow, startcol)`. You are also given a **0-indexed** string...
null
[Python3, Java, C++] Dictionary/Map and Prefix Sum O(n)
intervals-between-identical-elements
1
1
Dictionary/Hashmap is used to store all the occurences of a given number as {num: [indexes of occurences in arr]}\n\n***Explanation for the use of prefix array***:\nPrefix array `pre` is first used to fetch the sum of numbers uptil index i (for a given number arr[i]). We know that the numbers in the list are sorted thu...
45
You are given a **0-indexed** array of `n` integers `arr`. The **interval** between two elements in `arr` is defined as the **absolute difference** between their indices. More formally, the **interval** between `arr[i]` and `arr[j]` is `|i - j|`. Return _an array_ `intervals` _of length_ `n` _where_ `intervals[i]` _i...
null
[Python3] prefix sum
intervals-between-identical-elements
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/338b3e50d12cc0067b8b85e8e27c1b0c10fd91c6) for solutions of weely 273. \n\n```\nclass Solution:\n def getDistances(self, arr: List[int]) -> List[int]:\n loc = defaultdict(list)\n for i, x in enumerate(arr): loc[x].append(i)\n ...
10
You are given a **0-indexed** array of `n` integers `arr`. The **interval** between two elements in `arr` is defined as the **absolute difference** between their indices. More formally, the **interval** between `arr[i]` and `arr[j]` is `|i - j|`. Return _an array_ `intervals` _of length_ `n` _where_ `intervals[i]` _i...
null
Python | Simple Solution
intervals-between-identical-elements
0
1
# Intuition\nThis question is very similar to [1685. Sum of Absolute Differences in a Sorted Array](https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/description/)\n\n# Approach\n[Click Here](https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/solutions/4329588/python-s...
0
You are given a **0-indexed** array of `n` integers `arr`. The **interval** between two elements in `arr` is defined as the **absolute difference** between their indices. More formally, the **interval** between `arr[i]` and `arr[j]` is `|i - j|`. Return _an array_ `intervals` _of length_ `n` _where_ `intervals[i]` _i...
null
UGLY BUT BEGINNER FRIENDLY || BOTH SUFFIX & PREFIX || Python || LONG EXPLAINED
intervals-between-identical-elements
0
1
# Intuition\nSo, to find the intervals we can find the summ of all index seen from left side (prefix) and summ of all index seen from right side (suffix)\nnow the formula will be\n(prefix sum - (distance from left * index val)) + (suffix sum - (distance from right * index val))\n\n`now what is distance from left and di...
0
You are given a **0-indexed** array of `n` integers `arr`. The **interval** between two elements in `arr` is defined as the **absolute difference** between their indices. More formally, the **interval** between `arr[i]` and `arr[j]` is `|i - j|`. Return _an array_ `intervals` _of length_ `n` _where_ `intervals[i]` _i...
null
Prefix - Map
intervals-between-identical-elements
0
1
# Complexity\n```haskell\nTime complexity: O(n)\nSpace complexity: O(n)\n```\n\n# Code\n```python\nclass Solution:\n def getDistances(self, A: List[int]) -> List[int]:\n # Returns s.t. R[i] = sum(|i - j| for j in [0..i] if A[j] == 0)\n def f(A: List[int]) -> List[int]:\n R = [0 for _ in rang...
0
You are given a **0-indexed** array of `n` integers `arr`. The **interval** between two elements in `arr` is defined as the **absolute difference** between their indices. More formally, the **interval** between `arr[i]` and `arr[j]` is `|i - j|`. Return _an array_ `intervals` _of length_ `n` _where_ `intervals[i]` _i...
null
[Python3] brute-force
recover-the-original-array
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/338b3e50d12cc0067b8b85e8e27c1b0c10fd91c6) for solutions of weely 273. \n\n```\nclass Solution:\n def recoverArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n cnt = Counter(nums)\n for i in range(1, len(nums)): ...
12
Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:
N is very small, how can we use that? Can we check every possible quadruplet?
85+ in speed and memory using Python3
recover-the-original-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
Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:
N is very small, how can we use that? Can we check every possible quadruplet?
Python (Simple Maths)
recover-the-original-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
Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:
N is very small, how can we use that? Can we check every possible quadruplet?
Python Counter: Use it to its fullest. 98ms, fastest solution yet... for slow python.
recover-the-original-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMany solutions here cleverly create a counter, and yet iterate through each num in the full array to subtract matching pairs. We can do a little better though. Since we *have* the counter, we can iterate through that instead and remove wh...
0
Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:
N is very small, how can we use that? Can we check every possible quadruplet?
Python. Beats 100%.
recover-the-original-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. -->\nsort nums\n\ncreate a dictionary with Counter of all vals\n\ncreate a test array testing abs(nums[0] - nums[i]) for i in range(1,n//2+1)\n\nthe n//2+1 upperbound is in...
0
Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:
N is very small, how can we use that? Can we check every possible quadruplet?
Python Solution
check-if-all-as-appears-before-all-bs
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` consisting of **only** the characters `'a'` and `'b'`, return `true` _if **every**_ `'a'` _appears before **every**_ `'b'` _in the string_. Otherwise, return `false`. **Example 1:** **Input:** s = "aaabbb " **Output:** true **Explanation:** The 'a's are at indices 0, 1, and 2, while the 'b's are a...
The only way to get to room i+1 is when you are visiting room i and room i has been visited an even number of times. After visiting room i an odd number of times, you are required to visit room nextVisit[i] where nextVisit[i] <= i. It takes a fixed amount of days for you to come back from room nextVisit[i] to room i. T...
Python3||O(n)|| easy
check-if-all-as-appears-before-all-bs
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, ...
1
Given a string `s` consisting of **only** the characters `'a'` and `'b'`, return `true` _if **every**_ `'a'` _appears before **every**_ `'b'` _in the string_. Otherwise, return `false`. **Example 1:** **Input:** s = "aaabbb " **Output:** true **Explanation:** The 'a's are at indices 0, 1, and 2, while the 'b's are a...
The only way to get to room i+1 is when you are visiting room i and room i has been visited an even number of times. After visiting room i an odd number of times, you are required to visit room nextVisit[i] where nextVisit[i] <= i. It takes a fixed amount of days for you to come back from room nextVisit[i] to room i. T...
[Java/Python 3] Check if 'b' followed by 'a'.
check-if-all-as-appears-before-all-bs
1
1
**Method 1**\n\n```java\n public boolean checkString(String s) {\n for (int i = 1; i < s.length(); ++i) {\n if (s.charAt(i - 1) == \'b\' && s.charAt(i) == \'a\') {\n return false;\n }\n }\n return true;\n }\n```\n```python\n def checkString(self, s: str...
42
Given a string `s` consisting of **only** the characters `'a'` and `'b'`, return `true` _if **every**_ `'a'` _appears before **every**_ `'b'` _in the string_. Otherwise, return `false`. **Example 1:** **Input:** s = "aaabbb " **Output:** true **Explanation:** The 'a's are at indices 0, 1, and 2, while the 'b's are a...
The only way to get to room i+1 is when you are visiting room i and room i has been visited an even number of times. After visiting room i an odd number of times, you are required to visit room nextVisit[i] where nextVisit[i] <= i. It takes a fixed amount of days for you to come back from room nextVisit[i] to room i. T...
Python3 || Easy and simple solution.
check-if-all-as-appears-before-all-bs
0
1
# **Please \u2191(upvote) if you like the solution.**\n# Code\n```\nclass Solution:\n def checkString(self, s: str) -> bool:\n for i in range(len(s)):\n if s[i]==\'b\':\n if \'a\' in s[i+1:]:\n return False\n return True\n elif \'b\' not i...
1
Given a string `s` consisting of **only** the characters `'a'` and `'b'`, return `true` _if **every**_ `'a'` _appears before **every**_ `'b'` _in the string_. Otherwise, return `false`. **Example 1:** **Input:** s = "aaabbb " **Output:** true **Explanation:** The 'a's are at indices 0, 1, and 2, while the 'b's are a...
The only way to get to room i+1 is when you are visiting room i and room i has been visited an even number of times. After visiting room i an odd number of times, you are required to visit room nextVisit[i] where nextVisit[i] <= i. It takes a fixed amount of days for you to come back from room nextVisit[i] to room i. T...
Easy python solution 1 liner (Multiple approach)
check-if-all-as-appears-before-all-bs
0
1
```\ndef checkString(self, s: str) -> bool:\n return (\'\'.join(sorted(list(s))))==s\n```\n\n```\ndef checkString(self, s: str) -> bool:\n return "ba" not in s\n```
21
Given a string `s` consisting of **only** the characters `'a'` and `'b'`, return `true` _if **every**_ `'a'` _appears before **every**_ `'b'` _in the string_. Otherwise, return `false`. **Example 1:** **Input:** s = "aaabbb " **Output:** true **Explanation:** The 'a's are at indices 0, 1, and 2, while the 'b's are a...
The only way to get to room i+1 is when you are visiting room i and room i has been visited an even number of times. After visiting room i an odd number of times, you are required to visit room nextVisit[i] where nextVisit[i] <= i. It takes a fixed amount of days for you to come back from room nextVisit[i] to room i. T...
OneLiner Python3
check-if-all-as-appears-before-all-bs
0
1
\n\n# Code\n```\nclass Solution:\n def checkString(self, s: str) -> bool:\n return (s.count(\'ba\')) < 1\n```
1
Given a string `s` consisting of **only** the characters `'a'` and `'b'`, return `true` _if **every**_ `'a'` _appears before **every**_ `'b'` _in the string_. Otherwise, return `false`. **Example 1:** **Input:** s = "aaabbb " **Output:** true **Explanation:** The 'a's are at indices 0, 1, and 2, while the 'b's are a...
The only way to get to room i+1 is when you are visiting room i and room i has been visited an even number of times. After visiting room i an odd number of times, you are required to visit room nextVisit[i] where nextVisit[i] <= i. It takes a fixed amount of days for you to come back from room nextVisit[i] to room i. T...
Python3
number-of-laser-beams-in-a-bank
0
1
```\nclass Solution:\n def numberOfBeams(self, bank: List[str]) -> int:\n su = 0\n a = []\n for i in range(len(bank)):\n count = 0\n for j in range(len(bank[i])):\n if bank[i][j]==\'1\':\n count+=1\n if count>0:\n ...
2
Anti-theft security devices are activated inside a bank. You are given a **0-indexed** binary string array `bank` representing the floor plan of the bank, which is an `m x n` 2D matrix. `bank[i]` represents the `ith` row, consisting of `'0'`s and `'1'`s. `'0'` means the cell is empty, while`'1'` means the cell has a se...
Can we build a graph with all the prime numbers and the original array? We can use union-find to determine which indices are connected (i.e., which indices can be swapped).
Easily understanding Python Code with Detailed Explanation...
number-of-laser-beams-in-a-bank
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->Counting the no-of **ones** in each floor and appending hem to a list.\nIf only one floor has the security devices it is not possible to form a **Laser Beam** \nso a min of 2 floors are required t form a **Laser Beam**.\n\n**EG:** if there ...
1
Anti-theft security devices are activated inside a bank. You are given a **0-indexed** binary string array `bank` representing the floor plan of the bank, which is an `m x n` 2D matrix. `bank[i]` represents the `ith` row, consisting of `'0'`s and `'1'`s. `'0'` means the cell is empty, while`'1'` means the cell has a se...
Can we build a graph with all the prime numbers and the original array? We can use union-find to determine which indices are connected (i.e., which indices can be swapped).
Basic PYTHON STACK solution (If, elif approach) (beats 60% solutions)
number-of-laser-beams-in-a-bank
0
1
# Intuition\nBasic Python approach using Stack to keep track of previous laser device count\n\n# Approach\nmajor If Else approach using a stack to maintain the previous device count to generate the number of lasers between r1 and r2.\n\n# Complexity\n- Time complexity:\no(n*n)\n\n- Space complexity:\n- o(n)\n\n# Code\n...
1
Anti-theft security devices are activated inside a bank. You are given a **0-indexed** binary string array `bank` representing the floor plan of the bank, which is an `m x n` 2D matrix. `bank[i]` represents the `ith` row, consisting of `'0'`s and `'1'`s. `'0'` means the cell is empty, while`'1'` means the cell has a se...
Can we build a graph with all the prime numbers and the original array? We can use union-find to determine which indices are connected (i.e., which indices can be swapped).
Python || Easy To Understand || Beats 99% Time Complexity 🔥
number-of-laser-beams-in-a-bank
0
1
# Code\n```\nclass Solution:\n def numberOfBeams(self, bank: List[str]) -> int:\n arr = []\n for i in range(len(bank)):\n temp = bank[i].count("1")\n if temp > 0: arr.append(temp)\n cnt = 0\n for i in range(len(arr)-1):\n cnt += (arr[i] * arr[i+1])\n ...
1
Anti-theft security devices are activated inside a bank. You are given a **0-indexed** binary string array `bank` representing the floor plan of the bank, which is an `m x n` 2D matrix. `bank[i]` represents the `ith` row, consisting of `'0'`s and `'1'`s. `'0'` means the cell is empty, while`'1'` means the cell has a se...
Can we build a graph with all the prime numbers and the original array? We can use union-find to determine which indices are connected (i.e., which indices can be swapped).
Solution of number of laser beams in a bank problem || two-pointer algorithm
number-of-laser-beams-in-a-bank
0
1
# Approach\nSolved using two-pointer algorithm\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$ - as two-pointer algorithm takes linear time and \n.count() function takes linear time --> $$O(n*n)$$ == $$O(n^2)\n$$.\n- Space complexity:\n$$O(1)$$ - as, no extra space is required.\n\n# Code\n```\nclass Solution:\n def ...
1
Anti-theft security devices are activated inside a bank. You are given a **0-indexed** binary string array `bank` representing the floor plan of the bank, which is an `m x n` 2D matrix. `bank[i]` represents the `ith` row, consisting of `'0'`s and `'1'`s. `'0'` means the cell is empty, while`'1'` means the cell has a se...
Can we build a graph with all the prime numbers and the original array? We can use union-find to determine which indices are connected (i.e., which indices can be swapped).
[Python3, Java, C++] Simple O(mn)
number-of-laser-beams-in-a-bank
1
1
**Explanation**:\nTo find the total number of `laser beams` we have to do 2 things:\n1. Find the `number of laser beams` between \'adjacent rows\'. A row here is considered only if it has atleast 1 `security device`. Otherwise the row is simply ignored. \nThus if: \nRow `1`: 3 security...
66
Anti-theft security devices are activated inside a bank. You are given a **0-indexed** binary string array `bank` representing the floor plan of the bank, which is an `m x n` 2D matrix. `bank[i]` represents the `ith` row, consisting of `'0'`s and `'1'`s. `'0'` means the cell is empty, while`'1'` means the cell has a se...
Can we build a graph with all the prime numbers and the original array? We can use union-find to determine which indices are connected (i.e., which indices can be swapped).
Python3 Code: Runtime Beats 91% O(n) Memory Beats 90%
number-of-laser-beams-in-a-bank
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
Anti-theft security devices are activated inside a bank. You are given a **0-indexed** binary string array `bank` representing the floor plan of the bank, which is an `m x n` 2D matrix. `bank[i]` represents the `ith` row, consisting of `'0'`s and `'1'`s. `'0'` means the cell is empty, while`'1'` means the cell has a se...
Can we build a graph with all the prime numbers and the original array? We can use union-find to determine which indices are connected (i.e., which indices can be swapped).
2125. Number of Laser Beams in a Bank
number-of-laser-beams-in-a-bank
0
1
**EASY TO UNDERSTAND || BEGINNER FRIENDLY**\n```\n arr=[]\n \n for i in range(len(bank)):\n count=0\n for j in range(len(bank[i])):\n if bank[i][j]==\'1\':\n count+=1\n arr.append(count)\n\n ans=[]\n \n for ii i...
1
Anti-theft security devices are activated inside a bank. You are given a **0-indexed** binary string array `bank` representing the floor plan of the bank, which is an `m x n` 2D matrix. `bank[i]` represents the `ith` row, consisting of `'0'`s and `'1'`s. `'0'` means the cell is empty, while`'1'` means the cell has a se...
Can we build a graph with all the prime numbers and the original array? We can use union-find to determine which indices are connected (i.e., which indices can be swapped).
very simple solution | easy to understand
number-of-laser-beams-in-a-bank
0
1
```\nclass Solution:\n def numberOfBeams(self, bank: List[str]) -> int:\n prev, ans = 0, 0\n for i in bank:\n current = i.count(\'1\')\n if current:\n ans += prev * current\n prev = current\n return ans\n```
2
Anti-theft security devices are activated inside a bank. You are given a **0-indexed** binary string array `bank` representing the floor plan of the bank, which is an `m x n` 2D matrix. `bank[i]` represents the `ith` row, consisting of `'0'`s and `'1'`s. `'0'` means the cell is empty, while`'1'` means the cell has a se...
Can we build a graph with all the prime numbers and the original array? We can use union-find to determine which indices are connected (i.e., which indices can be swapped).
Python3 Simple Solution
number-of-laser-beams-in-a-bank
0
1
```\nclass Solution:\n def numberOfBeams(self, bank: List[str]) -> int:\n pre = 0\n nn = 0\n ans = 0\n for i in bank:\n nn= 0\n for j in i:\n if j == \'1\':\n nn+=1\n if nn:\n ans+=nn*pre\n pr...
1
Anti-theft security devices are activated inside a bank. You are given a **0-indexed** binary string array `bank` representing the floor plan of the bank, which is an `m x n` 2D matrix. `bank[i]` represents the `ith` row, consisting of `'0'`s and `'1'`s. `'0'` means the cell is empty, while`'1'` means the cell has a se...
Can we build a graph with all the prime numbers and the original array? We can use union-find to determine which indices are connected (i.e., which indices can be swapped).
[Python3] simulation
number-of-laser-beams-in-a-bank
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/18f88320ffb2c2a06e86fad46d82ebd17dadad64) for solutions of weekly 274. \n\n```\nclass Solution:\n def numberOfBeams(self, bank: List[str]) -> int:\n ans = prev = 0 \n for row in bank: \n curr = row.count(\'1\')\n ...
7
Anti-theft security devices are activated inside a bank. You are given a **0-indexed** binary string array `bank` representing the floor plan of the bank, which is an `m x n` 2D matrix. `bank[i]` represents the `ith` row, consisting of `'0'`s and `'1'`s. `'0'` means the cell is empty, while`'1'` means the cell has a se...
Can we build a graph with all the prime numbers and the original array? We can use union-find to determine which indices are connected (i.e., which indices can be swapped).
[Java/Python 3] Product of neighboring row devices number.
number-of-laser-beams-in-a-bank
1
1
**Q & A**\n\nQ1: How we got to know that we are required to do product of adjacent rows with count of 1s? \nA1: According to the problem:\nThere is one laser beam between any two security devices if both conditions are met:\n\n1. The two devices are located on two different rows: r1 and r2, where r1 < r2.\n2. For each ...
5
Anti-theft security devices are activated inside a bank. You are given a **0-indexed** binary string array `bank` representing the floor plan of the bank, which is an `m x n` 2D matrix. `bank[i]` represents the `ith` row, consisting of `'0'`s and `'1'`s. `'0'` means the cell is empty, while`'1'` means the cell has a se...
Can we build a graph with all the prime numbers and the original array? We can use union-find to determine which indices are connected (i.e., which indices can be swapped).
[PYTHON 3] 99.13% LESS MEMORY | 94.93% FASTER | EXPLANATION
number-of-laser-beams-in-a-bank
0
1
Runtime: **87 ms, faster than 94.93%** of Python3 online submissions for Number of Laser Beams in a Bank.\nMemory Usage: **15.9 MB, less than 99.13%** of Python3 online submissions for Number of Laser Beams in a Bank.\n\n```\nclass Solution:\n def numberOfBeams(self, bank: List[str]) -> int:\n a, s = [x.count...
9
Anti-theft security devices are activated inside a bank. You are given a **0-indexed** binary string array `bank` representing the floor plan of the bank, which is an `m x n` 2D matrix. `bank[i]` represents the `ith` row, consisting of `'0'`s and `'1'`s. `'0'` means the cell is empty, while`'1'` means the cell has a se...
Can we build a graph with all the prime numbers and the original array? We can use union-find to determine which indices are connected (i.e., which indices can be swapped).
[Java/Python 3] Sort then apply greedy algorithm.
destroying-asteroids
1
1
```java\n public boolean asteroidsDestroyed(int mass, int[] asteroids) {\n long m = mass;\n Arrays.sort(asteroids);\n for (int ast : asteroids) {\n if (m < ast) {\n return false;\n }\n m += ast;\n }\n return true;\n }\n```\nIn case...
23
You are given an integer `mass`, which represents the original mass of a planet. You are further given an integer array `asteroids`, where `asteroids[i]` is the mass of the `ith` asteroid. You can arrange for the planet to collide with the asteroids in **any arbitrary order**. If the mass of the planet is **greater th...
Can we reuse previously calculated information? How can we calculate the sum of the current subtree using the sum of the child's subtree?
Python | 90% faster than other... | Greedy Solution very intuitive | Using sorting technique
destroying-asteroids
0
1
![image](https://assets.leetcode.com/users/images/2853d186-23e7-414b-925b-f13588a50a2e_1658509474.4397042.png)\n***Please don\'t forget to upvote if found it helpful!!!***\n```\nclass Solution:\n def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:\n # ///// TC O(nlogn) //////\n aster...
1
You are given an integer `mass`, which represents the original mass of a planet. You are further given an integer array `asteroids`, where `asteroids[i]` is the mass of the `ith` asteroid. You can arrange for the planet to collide with the asteroids in **any arbitrary order**. If the mass of the planet is **greater th...
Can we reuse previously calculated information? How can we calculate the sum of the current subtree using the sum of the child's subtree?
✔Simple python solution | 85% lesser memory
destroying-asteroids
0
1
```\nclass Solution:\n def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:\n asteroids = sorted(asteroids)\n for i in asteroids:\n if i <= mass:\n mass += i\n else:\n return False\n return True\n```
2
You are given an integer `mass`, which represents the original mass of a planet. You are further given an integer array `asteroids`, where `asteroids[i]` is the mass of the `ith` asteroid. You can arrange for the planet to collide with the asteroids in **any arbitrary order**. If the mass of the planet is **greater th...
Can we reuse previously calculated information? How can we calculate the sum of the current subtree using the sum of the child's subtree?
BEATS 98.72% RUNTIME! My Solution :)
destroying-asteroids
0
1
# Intuition\nThe problem asks us to determine whether a given mass of asteroids can be destroyed by a spaceship. We can assume that the spaceship destroys asteroids by colliding with them. If an asteroid has a mass greater than the spaceship\'s current mass, it cannot destroy the asteroid, and the spaceship fails. Othe...
0
You are given an integer `mass`, which represents the original mass of a planet. You are further given an integer array `asteroids`, where `asteroids[i]` is the mass of the `ith` asteroid. You can arrange for the planet to collide with the asteroids in **any arbitrary order**. If the mass of the planet is **greater th...
Can we reuse previously calculated information? How can we calculate the sum of the current subtree using the sum of the child's subtree?
Simple Sort. Python3
destroying-asteroids
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 `mass`, which represents the original mass of a planet. You are further given an integer array `asteroids`, where `asteroids[i]` is the mass of the `ith` asteroid. You can arrange for the planet to collide with the asteroids in **any arbitrary order**. If the mass of the planet is **greater th...
Can we reuse previously calculated information? How can we calculate the sum of the current subtree using the sum of the child's subtree?
Heap. Python3. 95%+ mem
destroying-asteroids
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 `mass`, which represents the original mass of a planet. You are further given an integer array `asteroids`, where `asteroids[i]` is the mass of the `ith` asteroid. You can arrange for the planet to collide with the asteroids in **any arbitrary order**. If the mass of the planet is **greater th...
Can we reuse previously calculated information? How can we calculate the sum of the current subtree using the sum of the child's subtree?
Easy Python Solution
destroying-asteroids
0
1
# Code\n```\nclass Solution:\n def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:\n\n asteroids.sort()\n \n while asteroids:\n if mass >= asteroids[0]: \n mass = mass + asteroids[0]\n asteroids.pop(0)\n else: return False\n\...
0
You are given an integer `mass`, which represents the original mass of a planet. You are further given an integer array `asteroids`, where `asteroids[i]` is the mass of the `ith` asteroid. You can arrange for the planet to collide with the asteroids in **any arbitrary order**. If the mass of the planet is **greater th...
Can we reuse previously calculated information? How can we calculate the sum of the current subtree using the sum of the child's subtree?
Easy Python 3 solution
destroying-asteroids
0
1
\n# Code\n```\nclass Solution:\n def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:\n asteroids.sort()\n for i in asteroids:\n if mass < i:\n return False\n else:\n mass += i\n return True\n\n```
0
You are given an integer `mass`, which represents the original mass of a planet. You are further given an integer array `asteroids`, where `asteroids[i]` is the mass of the `ith` asteroid. You can arrange for the planet to collide with the asteroids in **any arbitrary order**. If the mass of the planet is **greater th...
Can we reuse previously calculated information? How can we calculate the sum of the current subtree using the sum of the child's subtree?
[Python3] Solution with using DFS approach and cycle detecting
maximum-employees-to-be-invited-to-a-meeting
0
1
# Code\n```\nclass Solution: \n def get_max_cycle_length(self, favorite: List[int]) -> int:\n person_cnt = len(favorite)\n max_cycle_length = 0\n\n seen = set()\n\n # for each person\n for i in range(person_cnt):\n # i - person i\n\n # if person not part of an...
3
A company is organizing a meeting and has a list of `n` employees, waiting to be invited. They have arranged for a large **circular** table, capable of seating **any number** of employees. The employees are numbered from `0` to `n - 1`. Each employee has a **favorite** person and they will attend the meeting **only if...
null
[Python 3] Self-Explainatory Code — O(N)
maximum-employees-to-be-invited-to-a-meeting
0
1
# Intuition\nOnly 2 candidates for an answer:\n* Longest cycle\n* Combination of cycles of length 2 with longest tails\n\n# Code\n```\nclass Solution:\n def maximumInvitations(self, favorite: List[int]) -> int:\n ans = 0\n n = len(favorite)\n cycles_of_2 = []\n seen = [False for _ in rang...
2
A company is organizing a meeting and has a list of `n` employees, waiting to be invited. They have arranged for a large **circular** table, capable of seating **any number** of employees. The employees are numbered from `0` to `n - 1`. Each employee has a **favorite** person and they will attend the meeting **only if...
null
[Python3] quite a tedious solution
maximum-employees-to-be-invited-to-a-meeting
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/18f88320ffb2c2a06e86fad46d82ebd17dadad64) for solutions of weekly 274. \n\n```\nclass Solution:\n def maximumInvitations(self, favorite: List[int]) -> int:\n n = len(favorite)\n graph = [[] for _ in range(n)]\n for i, x...
5
A company is organizing a meeting and has a list of `n` employees, waiting to be invited. They have arranged for a large **circular** table, capable of seating **any number** of employees. The employees are numbered from `0` to `n - 1`. Each employee has a **favorite** person and they will attend the meeting **only if...
null
Python, intutive approach. Beats 99% runtime and 100% space
maximum-employees-to-be-invited-to-a-meeting
0
1
# Intuition\nI looked at a couple of [solutions](https://leetcode.com/problems/maximum-employees-to-be-invited-to-a-meeting/submissions/1115462421/?source=submission-ac) to get this understanding. \n\nIn a levelwise visit we won\'t be able to visit nodes that form a circle\n\n\n# Approach\nWe visit levelwise and store ...
0
A company is organizing a meeting and has a list of `n` employees, waiting to be invited. They have arranged for a large **circular** table, capable of seating **any number** of employees. The employees are numbered from `0` to `n - 1`. Each employee has a **favorite** person and they will attend the meeting **only if...
null
Brief Python
maximum-employees-to-be-invited-to-a-meeting
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs stated in the most voted solutions, there are two things we need to consider in the graph formed by the employee favorites\n1 - The largest cycle\n2 - The segments that are self-contained\n\n# Approach\n<!-- Describe your approach to s...
0
A company is organizing a meeting and has a list of `n` employees, waiting to be invited. They have arranged for a large **circular** table, capable of seating **any number** of employees. The employees are numbered from `0` to `n - 1`. Each employee has a **favorite** person and they will attend the meeting **only if...
null
Fast solution without additional graph, using Floyd's cycle detection algorithm
maximum-employees-to-be-invited-to-a-meeting
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe\'re given an oriented graph in which every vertex has exactly one vertex coming out of it. In the final arrangement of employees, each vertex must sit next to its child.\n\nAfter a bit of thinking one realizes that the only possible ar...
0
A company is organizing a meeting and has a list of `n` employees, waiting to be invited. They have arranged for a large **circular** table, capable of seating **any number** of employees. The employees are numbered from `0` to `n - 1`. Each employee has a **favorite** person and they will attend the meeting **only if...
null
Reverse graph
maximum-employees-to-be-invited-to-a-meeting
0
1
# Intuition\nCatch loops and cycles, there can be only one cycle or many loops.\n\n# Approach\nFirstly create a reverse graph and catch pairs (the ones that are friends two each other)\nThen run the graph (dfs) starting from pairs, collecting loops depth.\nLastly run through all not vivsited people, catching biggest cy...
0
A company is organizing a meeting and has a list of `n` employees, waiting to be invited. They have arranged for a large **circular** table, capable of seating **any number** of employees. The employees are numbered from `0` to `n - 1`. Each employee has a **favorite** person and they will attend the meeting **only if...
null
Beats 99% | CodeDominar Solution
capitalize-the-title
0
1
# Code\n```\nclass Solution:\n def capitalizeTitle(self, title: str) -> str:\n li = title.split()\n for i,l in enumerate(li):\n if len(l) <= 2:\n li[i] = l.lower()\n else:\n li[i] = l[0].upper() + l[1:].lower()\n return \' \'.join(li)\n```
1
You are given a string `title` consisting of one or more words separated by a single space, where each word consists of English letters. **Capitalize** the string by changing the capitalization of each word such that: * If the length of the word is `1` or `2` letters, change all letters to lowercase. * Otherwise, ...
Store the rectangle height and width ratio in a hashmap. Traverse the ratios, and for each ratio, use the frequency of the ratio to add to the total pair count.
Python | 95% Beats | Using Lower and Capitalize
capitalize-the-title
0
1
# Submission Details:\nhttps://leetcode.com/problems/capitalize-the-title/submissions/881960588/\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def ca...
1
You are given a string `title` consisting of one or more words separated by a single space, where each word consists of English letters. **Capitalize** the string by changing the capitalization of each word such that: * If the length of the word is `1` or `2` letters, change all letters to lowercase. * Otherwise, ...
Store the rectangle height and width ratio in a hashmap. Traverse the ratios, and for each ratio, use the frequency of the ratio to add to the total pair count.
🏔Capitalization || 🔥Beat 100% in 9 lines🔥 || 😎Enjoy LeetCode...
capitalize-the-title
0
1
# KARRAR\n> Capitalize the TITLE of letters in the sentence...\n>> Optimized code...\n>>> Easily understand able...\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach:\n Lowest time complexity...\n If you want to beat the most PLEASE UPVOTE...\n\n\n<!--...
2
You are given a string `title` consisting of one or more words separated by a single space, where each word consists of English letters. **Capitalize** the string by changing the capitalization of each word such that: * If the length of the word is `1` or `2` letters, change all letters to lowercase. * Otherwise, ...
Store the rectangle height and width ratio in a hashmap. Traverse the ratios, and for each ratio, use the frequency of the ratio to add to the total pair count.
[Java/Python 3] Clean code w/ brief analysis.
capitalize-the-title
1
1
**Q & A**\nQ1: Where can I find the material about togglling letter cases in Java?\nA1: You can find [here](https://www.techiedelight.com/bit-hacks-part-4-playing-letters-english-alphabet/). - credit to **@Aaditya_Burujwale**\n\n**End of Q & A**\n\n----\n\n```java\n public String capitalizeTitle(String title) {\n ...
11
You are given a string `title` consisting of one or more words separated by a single space, where each word consists of English letters. **Capitalize** the string by changing the capitalization of each word such that: * If the length of the word is `1` or `2` letters, change all letters to lowercase. * Otherwise, ...
Store the rectangle height and width ratio in a hashmap. Traverse the ratios, and for each ratio, use the frequency of the ratio to add to the total pair count.
Python | Easy Solution✅
capitalize-the-title
0
1
```\ndef capitalizeTitle(self, title: str) -> str:\n output = list()\n word_arr = title.split()\n for word in word_arr:\n output.append(word.title()) if len(word) > 2 else output.append(word.lower())\n return " ".join(output)\n```
6
You are given a string `title` consisting of one or more words separated by a single space, where each word consists of English letters. **Capitalize** the string by changing the capitalization of each word such that: * If the length of the word is `1` or `2` letters, change all letters to lowercase. * Otherwise, ...
Store the rectangle height and width ratio in a hashmap. Traverse the ratios, and for each ratio, use the frequency of the ratio to add to the total pair count.
Python Easy Solution
capitalize-the-title
0
1
```\nclass Solution:\n def capitalizeTitle(self, title: str) -> str:\n title = title.split()\n word = ""\n for i in range(len(title)):\n if len(title[i]) < 3:\n word = word + title[i].lower() + " "\n else:\n word = word + title[i].capitalize() ...
5
You are given a string `title` consisting of one or more words separated by a single space, where each word consists of English letters. **Capitalize** the string by changing the capitalization of each word such that: * If the length of the word is `1` or `2` letters, change all letters to lowercase. * Otherwise, ...
Store the rectangle height and width ratio in a hashmap. Traverse the ratios, and for each ratio, use the frequency of the ratio to add to the total pair count.
Image Explanation🏆- [Fastest, Easiest & Concise] - C++/Java/Python
maximum-twin-sum-of-a-linked-list
1
1
# Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`Maximum Twin Sum of a Linked List` by `Aryan Mittal`\n![lc.png](https://assets.leetcode.com/users/images/c68c6de4-4912-4bd1-bb85-59eb6f111502_1684286771.1539989.png)\n\n\n# Approach & Intution\n![image.png](https://assets.leetcode.com/users/images/c84f966e-...
76
In a linked list of size `n`, where `n` is **even**, the `ith` node (**0-indexed**) of the linked list is known as the **twin** of the `(n-1-i)th` node, if `0 <= i <= (n / 2) - 1`. * For example, if `n = 4`, then node `0` is the twin of node `3`, and node `1` is the twin of node `2`. These are the only nodes with tw...
Could you generate all possible pairs of disjoint subsequences? Could you find the maximum length palindrome in each subsequence for a pair of disjoint subsequences?
C++ / Python mid and reverse solution
maximum-twin-sum-of-a-linked-list
0
1
**C++ :**\n\n```\nint pairSum(ListNode* head) {\n\tListNode* slow = head;\n\tListNode* fast = head;\n\tint maxVal = 0;\n\n\t// Get middle of linked list\n\twhile(fast && fast -> next)\n\t{\n\t\tfast = fast -> next -> next;\n\t\tslow = slow -> next;\n\t}\n\n\t// Reverse second part of linked list\n\tListNode *nextNode, ...
212
In a linked list of size `n`, where `n` is **even**, the `ith` node (**0-indexed**) of the linked list is known as the **twin** of the `(n-1-i)th` node, if `0 <= i <= (n / 2) - 1`. * For example, if `n = 4`, then node `0` is the twin of node `3`, and node `1` is the twin of node `2`. These are the only nodes with tw...
Could you generate all possible pairs of disjoint subsequences? Could you find the maximum length palindrome in each subsequence for a pair of disjoint subsequences?
using dictnory in TC=N
longest-palindrome-by-concatenating-two-letter-words
0
1
```\nclass Solution:\n def longestPalindrome(self, words: List[str]) -> int:\n dc=defaultdict(lambda:0)\n for a in words:\n dc[a]+=1\n count=0\n palindromswords=0\n inmiddle=0\n wds=set(words)\n for a in wds:\n if(a==a[::-1]):\n if...
5
You are given an array of strings `words`. Each element of `words` consists of **two** lowercase English letters. Create the **longest possible palindrome** by selecting some elements from `words` and concatenating them in **any order**. Each element can be selected **at most once**. Return _the **length** of the lon...
If the subtree doesn't contain 1, then the missing value will always be 1. What data structure allows us to dynamically update the values that are currently not present?
Python3 Hash map approach
longest-palindrome-by-concatenating-two-letter-words
0
1
\n**Main idea:**\n\nTo look at all possible types of variations of palindrome construction let\'s use the example: \n\n\twords = ["ab", "ee", "cc", "ba", "ee", "cc", "cc"]\n\nTo construct a palindrome we can use three types of "words":\n1. The same "word" as we met before, but at reversed order: \n\n\t\t"ab" + ... + "b...
2
You are given an array of strings `words`. Each element of `words` consists of **two** lowercase English letters. Create the **longest possible palindrome** by selecting some elements from `words` and concatenating them in **any order**. Each element can be selected **at most once**. Return _the **length** of the lon...
If the subtree doesn't contain 1, then the missing value will always be 1. What data structure allows us to dynamically update the values that are currently not present?
Easy python solution
longest-palindrome-by-concatenating-two-letter-words
0
1
\n\n# Code\n```\nclass Solution:\n def longestPalindrome(self, words: List[str]) -> int:\n ### count the frequency of each word in words\n counter = Counter(words)\n \n ### initialize res and mid. \n ### mid represent if result is in case1 (mid=1) or case2 (mid=0)\n res = mi...
1
You are given an array of strings `words`. Each element of `words` consists of **two** lowercase English letters. Create the **longest possible palindrome** by selecting some elements from `words` and concatenating them in **any order**. Each element can be selected **at most once**. Return _the **length** of the lon...
If the subtree doesn't contain 1, then the missing value will always be 1. What data structure allows us to dynamically update the values that are currently not present?
Simple and Easy, Python, O(n) time and space
longest-palindrome-by-concatenating-two-letter-words
0
1
# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def longestPalindrome(self, words: List[str]) -> int:\n map = {}\n occur = False\n co...
3
You are given an array of strings `words`. Each element of `words` consists of **two** lowercase English letters. Create the **longest possible palindrome** by selecting some elements from `words` and concatenating them in **any order**. Each element can be selected **at most once**. Return _the **length** of the lon...
If the subtree doesn't contain 1, then the missing value will always be 1. What data structure allows us to dynamically update the values that are currently not present?
Limited Premium Explained Solution
stamping-the-grid
1
1
\n```\nclass Solution:\n def possibleToStamp(self, grid, H, W):\n def acc_2d(grid):\n dp = [[0] * (n+1) for _ in range(m+1)] \n for c, r in product(range(n), range(m)):\n dp[r+1][c+1] = dp[r+1][c] + dp[r][c+1] - dp[r][c] + grid[r][c]\n return dp\n\n def s...
0
You are given an `m x n` binary matrix `grid` where each cell is either `0` (empty) or `1` (occupied). You are then given stamps of size `stampHeight x stampWidth`. We want to fit the stamps such that they follow the given **restrictions** and **requirements**: 1. Cover all the **empty** cells. 2. Do not cover any ...
When is it possible to convert original into a 2D array and when is it impossible? It is possible if and only if m * n == original.length If it is possible to convert original to a 2D array, keep an index i such that original[i] is the next element to add to the 2D array.
An incorrect but accepted solution,and the hacking testcase.
stamping-the-grid
0
1
### Source Code\n```Python\nclass Solution:\n def possibleToStamp(self, grid: List[List[int]], sh: int, sw: int) -> bool:\n n, m = len(grid) + 1, len(grid[0])\n grid.append([1] * m)\n\n f1 = [0] * m\n for row in grid:\n f2 = [0] * m\n l, r = 0, 0\n for j i...
0
You are given an `m x n` binary matrix `grid` where each cell is either `0` (empty) or `1` (occupied). You are then given stamps of size `stampHeight x stampWidth`. We want to fit the stamps such that they follow the given **restrictions** and **requirements**: 1. Cover all the **empty** cells. 2. Do not cover any ...
When is it possible to convert original into a 2D array and when is it impossible? It is possible if and only if m * n == original.length If it is possible to convert original to a 2D array, keep an index i such that original[i] is the next element to add to the 2D array.
[Java/Python 3] Two codes w/ brief analysis.
check-if-every-row-and-column-contains-all-numbers
1
1
**Q & A**\n\nQ: How does declaring sets inside 1st loop different from declaring ouside the loops?\nA: They only exist during each iteration of the outer loop; Therefore, we do NOT need to clear them after each iteration. Otherwise their life cycle will NOT terminate till the end of the whole code, and also we have to ...
69
An `n x n` matrix is **valid** if every row and every column contains **all** the integers from `1` to `n` (**inclusive**). Given an `n x n` integer matrix `matrix`, return `true` _if the matrix is **valid**._ Otherwise, return `false`. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[3,1,2\],\[2,3,1\]\] **Output:**...
Try to concatenate every two different strings from the list. Count the number of pairs with concatenation equals to target.
use DP tabulation
check-if-every-row-and-column-contains-all-numbers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
An `n x n` matrix is **valid** if every row and every column contains **all** the integers from `1` to `n` (**inclusive**). Given an `n x n` integer matrix `matrix`, return `true` _if the matrix is **valid**._ Otherwise, return `false`. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[3,1,2\],\[2,3,1\]\] **Output:**...
Try to concatenate every two different strings from the list. Count the number of pairs with concatenation equals to target.
Python3 simple 2 lines
check-if-every-row-and-column-contains-all-numbers
0
1
Create a set containing the integers from `1...n` then check that each set of rows and columns is equal to this set.\n\n`zip(*matrix)` is a convenient way of obtaining the columns of a matrix\n\n```python\n def checkValid(self, matrix: List[List[int]]) -> bool:\n set_ = set(range(1,len(matrix)+1))\n re...
26
An `n x n` matrix is **valid** if every row and every column contains **all** the integers from `1` to `n` (**inclusive**). Given an `n x n` integer matrix `matrix`, return `true` _if the matrix is **valid**._ Otherwise, return `false`. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[3,1,2\],\[2,3,1\]\] **Output:**...
Try to concatenate every two different strings from the list. Count the number of pairs with concatenation equals to target.
Python One-Liner
check-if-every-row-and-column-contains-all-numbers
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 `n x n` matrix is **valid** if every row and every column contains **all** the integers from `1` to `n` (**inclusive**). Given an `n x n` integer matrix `matrix`, return `true` _if the matrix is **valid**._ Otherwise, return `false`. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[3,1,2\],\[2,3,1\]\] **Output:**...
Try to concatenate every two different strings from the list. Count the number of pairs with concatenation equals to target.
Python (Simple Hashmap)
check-if-every-row-and-column-contains-all-numbers
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)$$ --...
4
An `n x n` matrix is **valid** if every row and every column contains **all** the integers from `1` to `n` (**inclusive**). Given an `n x n` integer matrix `matrix`, return `true` _if the matrix is **valid**._ Otherwise, return `false`. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[3,1,2\],\[2,3,1\]\] **Output:**...
Try to concatenate every two different strings from the list. Count the number of pairs with concatenation equals to target.
A simple and CORRECT XOR method
check-if-every-row-and-column-contains-all-numbers
0
1
As suggested by @kartik135065, \nsimple XOR method can be wrong as the code could not pass the test case such as [[1,2,2,4,5,6,6],[2,2,4,5,6,6,1],[2,4,5,6,6,1,2],[4,5,6,6,1,2,2],[5,6,6,1,2,2,4],[6,6,1,2,2,4,5],[6,1,2,2,4,5,6]]\n\nI crafted the correct codes using the XOR idea and easily passed the above test case. Pls ...
5
An `n x n` matrix is **valid** if every row and every column contains **all** the integers from `1` to `n` (**inclusive**). Given an `n x n` integer matrix `matrix`, return `true` _if the matrix is **valid**._ Otherwise, return `false`. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[3,1,2\],\[2,3,1\]\] **Output:**...
Try to concatenate every two different strings from the list. Count the number of pairs with concatenation equals to target.
✔Python 3 | 7 Line solution | 87% Faster runtime | 92.99% lesser memory
check-if-every-row-and-column-contains-all-numbers
0
1
```\nclass Solution:\n def checkValid(self, matrix: List[List[int]]) -> bool:\n lst = [0]*len(matrix)\n for i in matrix:\n if len(set(i)) != len(matrix):\n return False\n for j in range(len(i)):\n lst[j] += i[j]\n return len(set(lst)) == 1\n```
12
An `n x n` matrix is **valid** if every row and every column contains **all** the integers from `1` to `n` (**inclusive**). Given an `n x n` integer matrix `matrix`, return `true` _if the matrix is **valid**._ Otherwise, return `false`. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[3,1,2\],\[2,3,1\]\] **Output:**...
Try to concatenate every two different strings from the list. Count the number of pairs with concatenation equals to target.
Python easy | Set | 98% faster and memory efficient
check-if-every-row-and-column-contains-all-numbers
0
1
```\nclass Solution:\n def checkValid(self, matrix: List[List[int]]) -> bool:\n for r in range(len(matrix)):\n colSet = set()\n rowSet = set()\n for c in range(len(matrix)):\n if matrix[r][c] in colSet or matrix[c][r] in rowSet:\n return False...
3
An `n x n` matrix is **valid** if every row and every column contains **all** the integers from `1` to `n` (**inclusive**). Given an `n x n` integer matrix `matrix`, return `true` _if the matrix is **valid**._ Otherwise, return `false`. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[3,1,2\],\[2,3,1\]\] **Output:**...
Try to concatenate every two different strings from the list. Count the number of pairs with concatenation equals to target.
[Python3] 1-line
check-if-every-row-and-column-contains-all-numbers
0
1
Please checkout this [commit](https://github.com/gaosanyong/leetcode/commit/36536bdcdd42d372f17893d27ffbe283d970e24f) for solutions of weekly 275. \n\n```\nclass Solution:\n def checkValid(self, matrix: List[List[int]]) -> bool:\n return all(len(set(row)) == len(matrix) for row in matrix) and all(len(set(col)...
5
An `n x n` matrix is **valid** if every row and every column contains **all** the integers from `1` to `n` (**inclusive**). Given an `n x n` integer matrix `matrix`, return `true` _if the matrix is **valid**._ Otherwise, return `false`. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[3,1,2\],\[2,3,1\]\] **Output:**...
Try to concatenate every two different strings from the list. Count the number of pairs with concatenation equals to target.
[Python3, Java, C++] Easy Sliding Window O(n)
minimum-swaps-to-group-all-1s-together-ii
1
1
*Intuition*: \nWhenever you are faced with a circular array question, you can just append the array to itself to get rid of the circular array part of the problem\n\n***Explanation***:\n* Count number of ones in nums, let the number of ones be stored in the variable `ones`\n* Append nums to nums because we have to loo...
210
A **swap** is defined as taking two **distinct** positions in an array and swapping the values in them. A **circular** array is defined as an array where we consider the **first** element and the **last** element to be **adjacent**. Given a **binary** **circular** array `nums`, return _the minimum number of swaps req...
Can we use the maximum length at the previous position to help us find the answer for the current position? Can we use binary search to find the maximum consecutive same answer at every position?
Sliding window approach
minimum-swaps-to-group-all-1s-together-ii
0
1
**Approch Sliding window**\n\n* the main idea is that when it says it\'s circular you can use of doubling the array by it\'s self \n\n* another is that then main intuision is that it says `"to group all the one\'s"` well you have to ask how many `one\'s(1\'s)` there are in the orginal array then that will tell you the ...
1
A **swap** is defined as taking two **distinct** positions in an array and swapping the values in them. A **circular** array is defined as an array where we consider the **first** element and the **last** element to be **adjacent**. Given a **binary** **circular** array `nums`, return _the minimum number of swaps req...
Can we use the maximum length at the previous position to help us find the answer for the current position? Can we use binary search to find the maximum consecutive same answer at every position?
Sliding window with comments, Python
minimum-swaps-to-group-all-1s-together-ii
0
1
First, by appending nums to nums, you can ignore the effect of split case.\nThen, you look at the window whose width is `width`. Here, `width` = the number of 1\'s in the original nums. This is because you have to gather all 1\'s in this window at the end of some swap operations. Therefore, the number of swap operation...
22
A **swap** is defined as taking two **distinct** positions in an array and swapping the values in them. A **circular** array is defined as an array where we consider the **first** element and the **last** element to be **adjacent**. Given a **binary** **circular** array `nums`, return _the minimum number of swaps req...
Can we use the maximum length at the previous position to help us find the answer for the current position? Can we use binary search to find the maximum consecutive same answer at every position?
✔ Python3 Solution | Sliding Window | O(n) Time
minimum-swaps-to-group-all-1s-together-ii
0
1
`Time Complexity` : `O(n)`\n`Space Complexity` : `O(1)`\n```\nclass Solution:\n def minSwaps(self, nums):\n n, k, ans = len(nums), nums.count(1), float(\'inf\')\n c = nums[:k].count(1)\n for i in range(n):\n ans = min(ans, k - c)\n c += nums[(i + k) % n] - nums[i]\n ...
1
A **swap** is defined as taking two **distinct** positions in an array and swapping the values in them. A **circular** array is defined as an array where we consider the **first** element and the **last** element to be **adjacent**. Given a **binary** **circular** array `nums`, return _the minimum number of swaps req...
Can we use the maximum length at the previous position to help us find the answer for the current position? Can we use binary search to find the maximum consecutive same answer at every position?
[Java/Python 3] Sliding Window O(n) code w/ brief explanation and analysis.
minimum-swaps-to-group-all-1s-together-ii
1
1
Denote as `winWidth` the total number of `1`\'s in the input array, then the goal of swaps is to get a window of size `winWidth` full of `1`\'s. Therefore, we can maintain a sliding window of size `winWidth` to find the maximum `1`\'s inside, and accordingly the minimum number of `0`\'s inside the sliding window is the...
8
A **swap** is defined as taking two **distinct** positions in an array and swapping the values in them. A **circular** array is defined as an array where we consider the **first** element and the **last** element to be **adjacent**. Given a **binary** **circular** array `nums`, return _the minimum number of swaps req...
Can we use the maximum length at the previous position to help us find the answer for the current position? Can we use binary search to find the maximum consecutive same answer at every position?
Simple sliding window with Python
minimum-swaps-to-group-all-1s-together-ii
0
1
# Intuition\nWhen all ones are next to each other, they will form a subarray of the size of the total number of ones.\nWe can count the number of ones, divide the array into subarrays of this size and then count the number of ones in each subarray. The number of \'missing\' ones will be the number of needed swaps.\n<!-...
1
A **swap** is defined as taking two **distinct** positions in an array and swapping the values in them. A **circular** array is defined as an array where we consider the **first** element and the **last** element to be **adjacent**. Given a **binary** **circular** array `nums`, return _the minimum number of swaps req...
Can we use the maximum length at the previous position to help us find the answer for the current position? Can we use binary search to find the maximum consecutive same answer at every position?
Python sliding window O(n)
minimum-swaps-to-group-all-1s-together-ii
0
1
```\nclass Solution:\n def minSwaps(self, nums: List[int]) -> int:\n ones = nums.count(1)\n n = len(nums)\n res = ones\n start = 0\n end = ones-1\n zeroesInWindow = sum(num==0 for num in nums[start:end+1])\n \n while start < n:\n # print(start, end ,...
2
A **swap** is defined as taking two **distinct** positions in an array and swapping the values in them. A **circular** array is defined as an array where we consider the **first** element and the **last** element to be **adjacent**. Given a **binary** **circular** array `nums`, return _the minimum number of swaps req...
Can we use the maximum length at the previous position to help us find the answer for the current position? Can we use binary search to find the maximum consecutive same answer at every position?
Sliding Window Beginner Friendly
minimum-swaps-to-group-all-1s-together-ii
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)$$ --...
0
A **swap** is defined as taking two **distinct** positions in an array and swapping the values in them. A **circular** array is defined as an array where we consider the **first** element and the **last** element to be **adjacent**. Given a **binary** **circular** array `nums`, return _the minimum number of swaps req...
Can we use the maximum length at the previous position to help us find the answer for the current position? Can we use binary search to find the maximum consecutive same answer at every position?
[Python3] bitmask
count-words-obtained-after-adding-a-letter
0
1
Please checkout this [commit](https://github.com/gaosanyong/leetcode/commit/36536bdcdd42d372f17893d27ffbe283d970e24f) for solutions of weekly 275. \n\n```\nclass Solution:\n def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n seen = set()\n for word in startWords: \n ...
94
You are given two **0-indexed** arrays of strings `startWords` and `targetWords`. Each string consists of **lowercase English letters** only. For each string in `targetWords`, check if it is possible to choose a string from `startWords` and perform a **conversion operation** on it to be equal to that from `targetWords...
A pivot point splits the array into equal prefix and suffix. If no change is made to the array, the goal is to find the number of pivot p such that prefix[p-1] == suffix[p]. Consider how prefix and suffix will change when we change a number nums[i] to k. When sweeping through each element, can you find the total number...
Easy Python solution with comments
count-words-obtained-after-adding-a-letter
0
1
# Intuition\n- Words should be sorted to help match the different permutations. \n- It will be easier to remove letters from targetWords to match startWords than to add letters to startWords to match targetWords. \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your app...
1
You are given two **0-indexed** arrays of strings `startWords` and `targetWords`. Each string consists of **lowercase English letters** only. For each string in `targetWords`, check if it is possible to choose a string from `startWords` and perform a **conversion operation** on it to be equal to that from `targetWords...
A pivot point splits the array into equal prefix and suffix. If no change is made to the array, the goal is to find the number of pivot p such that prefix[p-1] == suffix[p]. Consider how prefix and suffix will change when we change a number nums[i] to k. When sweeping through each element, can you find the total number...
[Java/Python 3] Group anagrams by hash w/ brief explanation and analysis.
count-words-obtained-after-adding-a-letter
1
1
1. Use HashMap/dict to group the hashs of the anagrams in `startWords` by their lengths;\n2. Traverse `targetWords`, for each word, compute its hashs after remove one character; Then check if we can find the hashs among the HashMap/dict corresponding to `startWord`; If yes, increase the counter `cnt` by `1`;\n\n**Metho...
27
You are given two **0-indexed** arrays of strings `startWords` and `targetWords`. Each string consists of **lowercase English letters** only. For each string in `targetWords`, check if it is possible to choose a string from `startWords` and perform a **conversion operation** on it to be equal to that from `targetWords...
A pivot point splits the array into equal prefix and suffix. If no change is made to the array, the goal is to find the number of pivot p such that prefix[p-1] == suffix[p]. Consider how prefix and suffix will change when we change a number nums[i] to k. When sweeping through each element, can you find the total number...
Help with the testcase
count-words-obtained-after-adding-a-letter
0
1
My output is 253 and result is 254.\nCan every one tell me where\'s wrong logic?\n\n```\n["mgxfkirslbh","wpmsq","pxfouenr","lnq","vcomefldanb","gdsjz","xortwlsgevidjpc","kynjtdlpg","hmofavtbgykidw","bsefprtwxuamjih","yvuxreobngjp","ihbywqkteusjxl","ugh","auydixmtogrkve","ox","wvknsj","pyekgfcab","zsunrh","ecrpmxuw","mt...
10
You are given two **0-indexed** arrays of strings `startWords` and `targetWords`. Each string consists of **lowercase English letters** only. For each string in `targetWords`, check if it is possible to choose a string from `startWords` and perform a **conversion operation** on it to be equal to that from `targetWords...
A pivot point splits the array into equal prefix and suffix. If no change is made to the array, the goal is to find the number of pivot p such that prefix[p-1] == suffix[p]. Consider how prefix and suffix will change when we change a number nums[i] to k. When sweeping through each element, can you find the total number...
Clean Python, Using Set, No Sorting, Binary Char Representation
count-words-obtained-after-adding-a-letter
0
1
Let M be the number of startWords, N be the number of targetWords and 26 is the number of characters.\nRuntime is O(M x 26) to generate the startWords set\nRuntime is O(N x 26) to look up the targetWords in the startWords set\nRuntime O(M+N)\n\nThe next natural step would be to not use a binary tuple to represent the w...
6
You are given two **0-indexed** arrays of strings `startWords` and `targetWords`. Each string consists of **lowercase English letters** only. For each string in `targetWords`, check if it is possible to choose a string from `startWords` and perform a **conversion operation** on it to be equal to that from `targetWords...
A pivot point splits the array into equal prefix and suffix. If no change is made to the array, the goal is to find the number of pivot p such that prefix[p-1] == suffix[p]. Consider how prefix and suffix will change when we change a number nums[i] to k. When sweeping through each element, can you find the total number...
FASTEST GREEDY SOLUTION (7 LINES)
earliest-possible-day-of-full-bloom
0
1
```\nclass Solution:\n def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int:\n comb=[(plantTime[i],growTime[i]) for i in range(len(plantTime))]\n mx,passed_days=0,0\n comb.sort(key=lambda x:(-x[1],x[0]))\n for i in range(len(plantTime)):\n mx=max(mx,(pa...
5
You have `n` flower seeds. Every seed must be planted first before it can begin to grow, then bloom. Planting a seed takes time and so does the growth of a seed. You are given two **0-indexed** integer arrays `plantTime` and `growTime`, of length `n` each: * `plantTime[i]` is the number of **full days** it takes you...
null
Simplest solution for beginners
divide-a-string-into-groups-of-size-k
0
1
\n\n# Code\n```\nclass Solution:\n def divideString(self, s: str, k: int, fill: str) -> List[str]:\n res=[]\n for i in range(0,len(s),k):\n res.append(s[i:i+k])\n diff=abs(len(res[-1])-k)\n \n if len(res[-1])!=k:\n for i in range(diff):\n res[-1...
1
A string `s` can be partitioned into groups of size `k` using the following procedure: * The first group consists of the first `k` characters of the string, the second group consists of the next `k` characters of the string, and so on. Each character can be a part of **exactly one** group. * For the last group, if...
Use suffix/prefix arrays. prefix[i] records the maximum value in range (0, i - 1) inclusive. suffix[i] records the minimum value in range (i + 1, n - 1) inclusive.
Simple python solution
divide-a-string-into-groups-of-size-k
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
A string `s` can be partitioned into groups of size `k` using the following procedure: * The first group consists of the first `k` characters of the string, the second group consists of the next `k` characters of the string, and so on. Each character can be a part of **exactly one** group. * For the last group, if...
Use suffix/prefix arrays. prefix[i] records the maximum value in range (0, i - 1) inclusive. suffix[i] records the minimum value in range (i + 1, n - 1) inclusive.
Easy Python Solution | Faster than 84%
divide-a-string-into-groups-of-size-k
0
1
```\nclass Solution:\n def divideString(self, s: str, k: int, fill: str) -> List[str]:\n ans = []\n no_of_groups = math.ceil(len(s)/k)\n start = 0\n while no_of_groups>0:\n if s[start:start+k]:\n ans.append(s[start:start+k])\n else:\n an...
1
A string `s` can be partitioned into groups of size `k` using the following procedure: * The first group consists of the first `k` characters of the string, the second group consists of the next `k` characters of the string, and so on. Each character can be a part of **exactly one** group. * For the last group, if...
Use suffix/prefix arrays. prefix[i] records the maximum value in range (0, i - 1) inclusive. suffix[i] records the minimum value in range (i + 1, n - 1) inclusive.
Easy python solution
divide-a-string-into-groups-of-size-k
0
1
```\ndef divideString(self, s: str, k: int, fill: str) -> List[str]:\n l=[]\n if len(s)%k!=0:\n s+=fill*(k-len(s)%k)\n for i in range(0,len(s),k):\n l.append(s[i:i+k])\n return l\n```
10
A string `s` can be partitioned into groups of size `k` using the following procedure: * The first group consists of the first `k` characters of the string, the second group consists of the next `k` characters of the string, and so on. Each character can be a part of **exactly one** group. * For the last group, if...
Use suffix/prefix arrays. prefix[i] records the maximum value in range (0, i - 1) inclusive. suffix[i] records the minimum value in range (i + 1, n - 1) inclusive.
Python one liner
divide-a-string-into-groups-of-size-k
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\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def di...
3
A string `s` can be partitioned into groups of size `k` using the following procedure: * The first group consists of the first `k` characters of the string, the second group consists of the next `k` characters of the string, and so on. Each character can be a part of **exactly one** group. * For the last group, if...
Use suffix/prefix arrays. prefix[i] records the maximum value in range (0, i - 1) inclusive. suffix[i] records the minimum value in range (i + 1, n - 1) inclusive.
[PYTHON] Comments | Clean
divide-a-string-into-groups-of-size-k
0
1
```\nclass Solution:\n def divideString(self, s: str, k: int, fill: str) -> List[str]:\n while len(s)%k != 0:\n s += fill\n # checking until the string is dividable into k groups\n # if not, it will add the filler until it is\n \n c = []\n for x in range(0, len(s)...
3
A string `s` can be partitioned into groups of size `k` using the following procedure: * The first group consists of the first `k` characters of the string, the second group consists of the next `k` characters of the string, and so on. Each character can be a part of **exactly one** group. * For the last group, if...
Use suffix/prefix arrays. prefix[i] records the maximum value in range (0, i - 1) inclusive. suffix[i] records the minimum value in range (i + 1, n - 1) inclusive.
[Python3] simulation
divide-a-string-into-groups-of-size-k
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/210499523d9965e2d9dd5e1a6fbf67931233e41b) for solutions of weekly 276. \n\n```\nclass Solution:\n def divideString(self, s: str, k: int, fill: str) -> List[str]:\n ans = []\n for i in range(0, len(s), k): \n ss = s[...
5
A string `s` can be partitioned into groups of size `k` using the following procedure: * The first group consists of the first `k` characters of the string, the second group consists of the next `k` characters of the string, and so on. Each character can be a part of **exactly one** group. * For the last group, if...
Use suffix/prefix arrays. prefix[i] records the maximum value in range (0, i - 1) inclusive. suffix[i] records the minimum value in range (i + 1, n - 1) inclusive.
Easy python solution
divide-a-string-into-groups-of-size-k
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
A string `s` can be partitioned into groups of size `k` using the following procedure: * The first group consists of the first `k` characters of the string, the second group consists of the next `k` characters of the string, and so on. Each character can be a part of **exactly one** group. * For the last group, if...
Use suffix/prefix arrays. prefix[i] records the maximum value in range (0, i - 1) inclusive. suffix[i] records the minimum value in range (i + 1, n - 1) inclusive.
Easy and simple solution || python3
divide-a-string-into-groups-of-size-k
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
A string `s` can be partitioned into groups of size `k` using the following procedure: * The first group consists of the first `k` characters of the string, the second group consists of the next `k` characters of the string, and so on. Each character can be a part of **exactly one** group. * For the last group, if...
Use suffix/prefix arrays. prefix[i] records the maximum value in range (0, i - 1) inclusive. suffix[i] records the minimum value in range (i + 1, n - 1) inclusive.
2138. Divide a String Into Groups of Size k
divide-a-string-into-groups-of-size-k
0
1
# Intuition\nCheers\n\n# Approach\nString slicing\n\n# Complexity\n- Time complexity:\n $$O(n): 17.30 MB$$\n\n- Space complexity:\n $$O(n): 35ms$$\n\n# Code\n```\nclass Solution:\n def divideString(self, s: str, k: int, fill: str) -> List[str]:\n assert 1<=len(s) and len(s)<=100, \'constraint reached\'\n ...
0
A string `s` can be partitioned into groups of size `k` using the following procedure: * The first group consists of the first `k` characters of the string, the second group consists of the next `k` characters of the string, and so on. Each character can be a part of **exactly one** group. * For the last group, if...
Use suffix/prefix arrays. prefix[i] records the maximum value in range (0, i - 1) inclusive. suffix[i] records the minimum value in range (i + 1, n - 1) inclusive.
Simple python solution beats 90%
minimum-moves-to-reach-target-score
0
1
# Intuition\nThe problem involves reaching the target integer starting from 1 using two operations: incrementing by one or doubling the current integer. We need to find the minimum number of moves required to reach the target, with the restriction that we can only use the double operation at most maxDoubles times. \n\n...
0
You are playing a game with integers. You start with the integer `1` and you want to reach the integer `target`. In one move, you can either: * **Increment** the current integer by one (i.e., `x = x + 1`). * **Double** the current integer (i.e., `x = 2 * x`). You can use the **increment** operation **any** numbe...
Maintain the frequency of all the points in a hash map. Traverse the hash map and if any point has the same y-coordinate as the query point, consider this point and the query point to form one of the horizontal lines of the square.
🐍Python3 the 🔥most easy 🔥way || Beginner friendly🔥🔥
solving-questions-with-brainpower
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Dynamic Programing or Memoization**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- we have array in given question, so we can think of something related to index.\n- problem states that i can skip or take the ...
1
You are given a **0-indexed** 2D integer array `questions` where `questions[i] = [pointsi, brainpoweri]`. The array describes the questions of an exam, where you have to process the questions **in order** (i.e., starting from question `0`) and make a decision whether to **solve** or **skip** each question. Solving que...
The length of the longest subsequence does not exceed n/k. Do you know why? Find the characters that could be included in the potential answer. A character occurring more than or equal to k times can be used in the answer up to (count of the character / k) times. Try all possible candidates in reverse lexicographic ord...
SORT SOLUTIONS🔥 PYTHON😊 CODE 👍UPVOTED
solving-questions-with-brainpower
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** 2D integer array `questions` where `questions[i] = [pointsi, brainpoweri]`. The array describes the questions of an exam, where you have to process the questions **in order** (i.e., starting from question `0`) and make a decision whether to **solve** or **skip** each question. Solving que...
The length of the longest subsequence does not exceed n/k. Do you know why? Find the characters that could be included in the potential answer. A character occurring more than or equal to k times can be used in the answer up to (count of the character / k) times. Try all possible candidates in reverse lexicographic ord...
[Python] From recursive to iterative, easy to understand 🔥🔥🔥
solving-questions-with-brainpower
0
1
# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def mostPoints(self, questions: List[List[int]]) -> int:\n memo = [-1] * len(questions)\n def dp(i):\n if i >= len(questions):\n return 0\n \n if memo[i] !...
1
You are given a **0-indexed** 2D integer array `questions` where `questions[i] = [pointsi, brainpoweri]`. The array describes the questions of an exam, where you have to process the questions **in order** (i.e., starting from question `0`) and make a decision whether to **solve** or **skip** each question. Solving que...
The length of the longest subsequence does not exceed n/k. Do you know why? Find the characters that could be included in the potential answer. A character occurring more than or equal to k times can be used in the answer up to (count of the character / k) times. Try all possible candidates in reverse lexicographic ord...
python3 Solution
solving-questions-with-brainpower
0
1
\n```\nclass Solution:\n def mostPoints(self, questions: List[List[int]]) -> int:\n n=len(questions)\n best=[0]*(n+1)\n @cache\n def go(i):\n if i>=n:\n return 0\n\n best=0\n best=max(go(i+1),best)\n best=max(go(i+questions[i][1]+...
1
You are given a **0-indexed** 2D integer array `questions` where `questions[i] = [pointsi, brainpoweri]`. The array describes the questions of an exam, where you have to process the questions **in order** (i.e., starting from question `0`) and make a decision whether to **solve** or **skip** each question. Solving que...
The length of the longest subsequence does not exceed n/k. Do you know why? Find the characters that could be included in the potential answer. A character occurring more than or equal to k times can be used in the answer up to (count of the character / k) times. Try all possible candidates in reverse lexicographic ord...