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
Simple python3 solution || beats 80% || 💻🧑‍💻🤖
final-value-of-variable-after-performing-operations
0
1
# ***These 2 solutions are Basically same***\n**Please upvote\nGuys if you have better solution please comment it**\n\n# Code 1\n```\nclass Solution:\n def finalValueAfterOperations(self, operations: List[str]) -> int:\n x=0\n for i in operations:\n if i=="--X" or i=="X--":\n ...
3
There is a programming language with only **four** operations and **one** variable `X`: * `++X` and `X++` **increments** the value of the variable `X` by `1`. * `--X` and `X--` **decrements** the value of the variable `X` by `1`. Initially, the value of `X` is `0`. Given an array of strings `operations` containi...
Note that if the number is negative it's the same as positive but you look for the minimum instead. In the case of maximum, if s[i] < x it's optimal that x is put before s[i]. In the case of minimum, if s[i] > x it's optimal that x is put before s[i].
Python Accumulate Max and Min
sum-of-beauty-in-the-array
0
1
```\nclass Solution:\n def sumOfBeauties(self, nums: List[int]) -> int:\n nums1 = list(accumulate(nums, lambda x, y: max(x, y)))\n nums2 = list(accumulate(nums[::-1], lambda x, y: min(x, y)))[::-1]\n cnt = 0\n for i in range(1, len(nums) - 1):\n if nums1[i - 1] < nums[i] < nums...
1
You are given a **0-indexed** integer array `nums`. For each index `i` (`1 <= i <= nums.length - 2`) the **beauty** of `nums[i]` equals: * `2`, if `nums[j] < nums[i] < nums[k]`, for **all** `0 <= j < i` and for **all** `i < k <= nums.length - 1`. * `1`, if `nums[i - 1] < nums[i] < nums[i + 1]`, and the previous co...
You can maintain a Heap of available Servers and a Heap of unavailable servers Note that the tasks will be processed in the input order so you just need to find the x-th server that will be available according to the rules
python3 precomputation
sum-of-beauty-in-the-array
0
1
\n\n\n\n* **Case1**: for each index in nums if every element before this is smaller and every element after this is bigger \nthan we have to increase count by 2\nfor this can we can make two array which will store minimum and maximum till now for each index\n* **Case2**: simply compare with left and right neighbour ,if...
18
You are given a **0-indexed** integer array `nums`. For each index `i` (`1 <= i <= nums.length - 2`) the **beauty** of `nums[i]` equals: * `2`, if `nums[j] < nums[i] < nums[k]`, for **all** `0 <= j < i` and for **all** `i < k <= nums.length - 1`. * `1`, if `nums[i - 1] < nums[i] < nums[i + 1]`, and the previous co...
You can maintain a Heap of available Servers and a Heap of unavailable servers Note that the tasks will be processed in the input order so you just need to find the x-th server that will be available according to the rules
Python | Two Passes | O(n)
sum-of-beauty-in-the-array
0
1
# Code\n```\nclass Solution:\n def sumOfBeauties(self, nums: List[int]) -> int:\n n = len(nums)\n d = [0]*n\n d[-1] = nums[-1]\n for i in range(n-2,-1,-1):\n d[i] = min(d[i+1], nums[i])\n curmax = nums[0]\n res = 0\n for i in range(1,n-1):\n if c...
2
You are given a **0-indexed** integer array `nums`. For each index `i` (`1 <= i <= nums.length - 2`) the **beauty** of `nums[i]` equals: * `2`, if `nums[j] < nums[i] < nums[k]`, for **all** `0 <= j < i` and for **all** `i < k <= nums.length - 1`. * `1`, if `nums[i - 1] < nums[i] < nums[i + 1]`, and the previous co...
You can maintain a Heap of available Servers and a Heap of unavailable servers Note that the tasks will be processed in the input order so you just need to find the x-th server that will be available according to the rules
intuitive approach
sum-of-beauty-in-the-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can simply keep track of the maximum value to the left of every index and minimum value to the RIGHT of every index in 2 seperate arrays, maxLeft and minRight. for every index, if the maximum to its left is LESS than it, every element ...
0
You are given a **0-indexed** integer array `nums`. For each index `i` (`1 <= i <= nums.length - 2`) the **beauty** of `nums[i]` equals: * `2`, if `nums[j] < nums[i] < nums[k]`, for **all** `0 <= j < i` and for **all** `i < k <= nums.length - 1`. * `1`, if `nums[i - 1] < nums[i] < nums[i + 1]`, and the previous co...
You can maintain a Heap of available Servers and a Heap of unavailable servers Note that the tasks will be processed in the input order so you just need to find the x-th server that will be available according to the rules
Python Simple Solution Explained
sum-of-beauty-in-the-array
0
1
# Intuition\nSo, to basically find beauty of an array we need to check for two conditions at each element of array.\n1. nums[j] < nums[i] < nums[k] -> for all j < i < k\n2. nums[i-1] < nums[i] < nums[i+1] \n\nLets break down the first condition,\nIt means for all the elements seen before i they all must be smaller tha...
0
You are given a **0-indexed** integer array `nums`. For each index `i` (`1 <= i <= nums.length - 2`) the **beauty** of `nums[i]` equals: * `2`, if `nums[j] < nums[i] < nums[k]`, for **all** `0 <= j < i` and for **all** `i < k <= nums.length - 1`. * `1`, if `nums[i - 1] < nums[i] < nums[i + 1]`, and the previous co...
You can maintain a Heap of available Servers and a Heap of unavailable servers Note that the tasks will be processed in the input order so you just need to find the x-th server that will be available according to the rules
space exchange for time, Beats 100.00%of users with Python3
sum-of-beauty-in-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:\nBeats 100.00%of users with Python3\n\n- Space complexity:\nBeats 25.84%of users with Python3\n\n# Code\n```\nclass Solution:\n d...
0
You are given a **0-indexed** integer array `nums`. For each index `i` (`1 <= i <= nums.length - 2`) the **beauty** of `nums[i]` equals: * `2`, if `nums[j] < nums[i] < nums[k]`, for **all** `0 <= j < i` and for **all** `i < k <= nums.length - 1`. * `1`, if `nums[i - 1] < nums[i] < nums[i + 1]`, and the previous co...
You can maintain a Heap of available Servers and a Heap of unavailable servers Note that the tasks will be processed in the input order so you just need to find the x-th server that will be available according to the rules
Python3 | Simple, Fast, Elegant | Beats 90%
detect-squares
0
1
# Please upvote if helpful!\n\n# Approach\n**Adding Points** - Since duplicate points can be used to form distinct, countable squares, we will use a dictionary to track the number of times that point has been added. In order for us to track the point in a dictionary, it must be hashable, so we will convert the point fr...
8
You are given a stream of points on the X-Y plane. Design an algorithm that: * **Adds** new points from the stream into a data structure. **Duplicate** points are allowed and should be treated as different points. * Given a query point, **counts** the number of ways to choose three points from the data structure s...
Is there something you can keep track of from one road to another? How would knowing the start time for each state help us solve the problem?
O(n) time | O(1) space | solution explained
detect-squares
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse a hashmap to add and count the points.\n\nWe are given a query point and need to choose the other three points and find the number of squares with a positive area. \n\nFor a square, we need four points. 1st point P1 is the query point...
2
You are given a stream of points on the X-Y plane. Design an algorithm that: * **Adds** new points from the stream into a data structure. **Duplicate** points are allowed and should be treated as different points. * Given a query point, **counts** the number of ways to choose three points from the data structure s...
Is there something you can keep track of from one road to another? How would knowing the start time for each state help us solve the problem?
[Python3] bfs
longest-subsequence-repeated-k-times
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/acb743eb49f794773b70483bbd90cd6403c367b3) for solutions of weekly 259. \n```\nclass Solution:\n def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:\n freq = [0] * 26\n for ch in s: freq[ord(ch)-97] += 1\n \n ...
11
You are given a string `s` of length `n`, and an integer `k`. You are tasked to find the **longest subsequence repeated** `k` times in string `s`. A **subsequence** is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A subsequen...
null
simple python bfs implementation
longest-subsequence-repeated-k-times
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)$$ -->\nn = len(s)\nlongestSubsequenceRepeatedK is O(n)\nso total time complexity wi...
0
You are given a string `s` of length `n`, and an integer `k`. You are tasked to find the **longest subsequence repeated** `k` times in string `s`. A **subsequence** is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A subsequen...
null
python3: 2 solutions
longest-subsequence-repeated-k-times
0
1
* In both solutions the helper functions do the same thing. It calculates if the **subString** belongs to **string** but the second (that uses an iterator) is fastest.\n\n\n**First solution**\n```\nclass Solution:\n def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:\n def helper(subString, string):...
0
You are given a string `s` of length `n`, and an integer `k`. You are tasked to find the **longest subsequence repeated** `k` times in string `s`. A **subsequence** is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A subsequen...
null
Simple python solution
maximum-difference-between-increasing-elements
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` of size `n`, find the **maximum difference** between `nums[i]` and `nums[j]` (i.e., `nums[j] - nums[i]`), such that `0 <= i < j < n` and `nums[i] < nums[j]`. Return _the **maximum difference**._ If no such `i` and `j` exists, return `-1`. **Example 1:** **Input:** nums = \[...
Sort the array. Try to reduce all elements with maximum value to the next maximum value in one operation.
Simple Solution and Simple Logic in Python
maximum-difference-between-increasing-elements
0
1
# Code\n```\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n difference = 0\n for i in range(len(nums)):\n for j in range(i,len(nums)):\n if nums[j]-nums[i]>difference:\n difference = nums[j]-nums[i]\n if difference == 0:\n ...
0
Given a **0-indexed** integer array `nums` of size `n`, find the **maximum difference** between `nums[i]` and `nums[j]` (i.e., `nums[j] - nums[i]`), such that `0 <= i < j < n` and `nums[i] < nums[j]`. Return _the **maximum difference**._ If no such `i` and `j` exists, return `-1`. **Example 1:** **Input:** nums = \[...
Sort the array. Try to reduce all elements with maximum value to the next maximum value in one operation.
Python simple one pass solution
maximum-difference-between-increasing-elements
0
1
**Python :**\n\n```\ndef maximumDifference(self, nums: List[int]) -> int:\n\tmaxDiff = -1\n\n\tminNum = nums[0]\n\n\tfor i in range(len(nums)):\n\t\tmaxDiff = max(maxDiff, nums[i] - minNum)\n\t\tminNum = min(minNum, nums[i])\n\n\treturn maxDiff if maxDiff != 0 else -1\n```\n\n**Like it ? please upvote !**
35
Given a **0-indexed** integer array `nums` of size `n`, find the **maximum difference** between `nums[i]` and `nums[j]` (i.e., `nums[j] - nums[i]`), such that `0 <= i < j < n` and `nums[i] < nums[j]`. Return _the **maximum difference**._ If no such `i` and `j` exists, return `-1`. **Example 1:** **Input:** nums = \[...
Sort the array. Try to reduce all elements with maximum value to the next maximum value in one operation.
[Java/Python 3] Time O(n) space O(1) codes w/ brief explanation and a similar problem.
maximum-difference-between-increasing-elements
1
1
**Similar Problem:** [121. Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock)\n\n----\n\nTraverse input, compare current number to the minimum of the previous ones. then update the max difference.\n```java\n public int maximumDifference(int[] nums) {\n int diff = -...
30
Given a **0-indexed** integer array `nums` of size `n`, find the **maximum difference** between `nums[i]` and `nums[j]` (i.e., `nums[j] - nums[i]`), such that `0 <= i < j < n` and `nums[i] < nums[j]`. Return _the **maximum difference**._ If no such `i` and `j` exists, return `-1`. **Example 1:** **Input:** nums = \[...
Sort the array. Try to reduce all elements with maximum value to the next maximum value in one operation.
[Python3] prefix min
maximum-difference-between-increasing-elements
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/fa0bb65b4cb428452e2b4192ad53e56393b8fb8d) for solutions of weekly 260. \n```\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n ans = -1 \n prefix = inf\n for i, x in enumerate(nums): \n ...
6
Given a **0-indexed** integer array `nums` of size `n`, find the **maximum difference** between `nums[i]` and `nums[j]` (i.e., `nums[j] - nums[i]`), such that `0 <= i < j < n` and `nums[i] < nums[j]`. Return _the **maximum difference**._ If no such `i` and `j` exists, return `-1`. **Example 1:** **Input:** nums = \[...
Sort the array. Try to reduce all elements with maximum value to the next maximum value in one operation.
[Python3] Straightforward O(n) no extra space w comments
maximum-difference-between-increasing-elements
0
1
```py\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n output = -1\n low = 10**9 # Set because of question constraints\n \n for i in range(len(nums)):\n # If we come across a new lowest number, keep track of it\n low = min(low, nums[i])\n ...
2
Given a **0-indexed** integer array `nums` of size `n`, find the **maximum difference** between `nums[i]` and `nums[j]` (i.e., `nums[j] - nums[i]`), such that `0 <= i < j < n` and `nums[i] < nums[j]`. Return _the **maximum difference**._ If no such `i` and `j` exists, return `-1`. **Example 1:** **Input:** nums = \[...
Sort the array. Try to reduce all elements with maximum value to the next maximum value in one operation.
linear time constant space 96% beat time complexity
grid-game
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 array `grid` of size `2 x n`, where `grid[r][c]` represents the number of points at position `(r, c)` on the matrix. Two robots are playing a game on this matrix. Both robots initially start at `(0, 0)` and want to reach `(1, n-1)`. Each robot may only move to the **right** (`(r, c)` t...
Note what actually matters is how many 0s and 1s are in odd and even positions For every cyclic shift we need to count how many 0s and 1s are at each parity and convert the minimum between them for each parity
[Java/Python 3] Prefix and Suffix sum O(n) code, w/ brief explanation and analysis.
grid-game
1
1
Key observation: **Robot 2 can ONLY choose the lower left part or the upper right part of the the column that Rob 1 traversed.** Therefore, we compute the *max values* of the two parts when traversing the two-cell-columns from left and right. The mininum out of the afore-mentioned *max values* is the solution.\n```java...
13
You are given a **0-indexed** 2D array `grid` of size `2 x n`, where `grid[r][c]` represents the number of points at position `(r, c)` on the matrix. Two robots are playing a game on this matrix. Both robots initially start at `(0, 0)` and want to reach `(1, n-1)`. Each robot may only move to the **right** (`(r, c)` t...
Note what actually matters is how many 0s and 1s are in odd and even positions For every cyclic shift we need to count how many 0s and 1s are at each parity and convert the minimum between them for each parity
Practice - DP solution that would work if A wasn't an A-hole.
grid-game
0
1
Note: **Dynamic-Programming approach does not work for this problem.** The idea behind a DP approach is to let Robot A go first, get the highest score it can get and then reduce all the grid-cells it passed through to 0. Then let Robot B go and get the highest score it can get. (the code below) But the question wants ...
6
You are given a **0-indexed** 2D array `grid` of size `2 x n`, where `grid[r][c]` represents the number of points at position `(r, c)` on the matrix. Two robots are playing a game on this matrix. Both robots initially start at `(0, 0)` and want to reach `(1, n-1)`. Each robot may only move to the **right** (`(r, c)` t...
Note what actually matters is how many 0s and 1s are in odd and even positions For every cyclic shift we need to count how many 0s and 1s are at each parity and convert the minimum between them for each parity
Simple python3 solution | Prefix sum + Suffix_sum
grid-game
0
1
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nclass Solution:\n def gridGame(self, grid: List[List[int]]) -> int:\n suffix_first = sum(grid[0])\...
0
You are given a **0-indexed** 2D array `grid` of size `2 x n`, where `grid[r][c]` represents the number of points at position `(r, c)` on the matrix. Two robots are playing a game on this matrix. Both robots initially start at `(0, 0)` and want to reach `(1, n-1)`. Each robot may only move to the **right** (`(r, c)` t...
Note what actually matters is how many 0s and 1s are in odd and even positions For every cyclic shift we need to count how many 0s and 1s are at each parity and convert the minimum between them for each parity
Sliding Window or Prefix Sum
grid-game
0
1
\n# Code\n```\nclass Solution:\n def gridGame(self, grid: List[List[int]]) -> int:\n mPoints = float(\'inf\')\n p1 = sum(grid[0])\n p2= -grid[1][-1]\n for i in range(len(grid[0])):\n p1 -=grid[0][i]\n p2 += grid[1][i-1]\n mPoints = min(mPoints, max(p1, p2)...
0
You are given a **0-indexed** 2D array `grid` of size `2 x n`, where `grid[r][c]` represents the number of points at position `(r, c)` on the matrix. Two robots are playing a game on this matrix. Both robots initially start at `(0, 0)` and want to reach `(1, n-1)`. Each robot may only move to the **right** (`(r, c)` t...
Note what actually matters is how many 0s and 1s are in odd and even positions For every cyclic shift we need to count how many 0s and 1s are at each parity and convert the minimum between them for each parity
Python3 solution
grid-game
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 gridGame(self, grid: List[List[int]]) -> int:\n N = len(grid[0])\n pre1,pre2 = g...
0
You are given a **0-indexed** 2D array `grid` of size `2 x n`, where `grid[r][c]` represents the number of points at position `(r, c)` on the matrix. Two robots are playing a game on this matrix. Both robots initially start at `(0, 0)` and want to reach `(1, n-1)`. Each robot may only move to the **right** (`(r, c)` t...
Note what actually matters is how many 0s and 1s are in odd and even positions For every cyclic shift we need to count how many 0s and 1s are at each parity and convert the minimum between them for each parity
Using Prefix Sum
grid-game
0
1
# Intuition\nFor every index calculating maximum score second robot can achieve and returning minimum score among all the indices.\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...
0
You are given a **0-indexed** 2D array `grid` of size `2 x n`, where `grid[r][c]` represents the number of points at position `(r, c)` on the matrix. Two robots are playing a game on this matrix. Both robots initially start at `(0, 0)` and want to reach `(1, n-1)`. Each robot may only move to the **right** (`(r, c)` t...
Note what actually matters is how many 0s and 1s are in odd and even positions For every cyclic shift we need to count how many 0s and 1s are at each parity and convert the minimum between them for each parity
Easiest Python
check-if-word-can-be-placed-in-crossword
0
1
# Intuition\ncheck all the valid spaces where this condition is met\n(previous cell is # or out of bounds and curr cell is not \'#\')\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...
0
You are given an `m x n` matrix `board`, representing the **current** state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), `' '` to represent any **empty** cells, and `'#'` to represent any **blocked** cells. A word can be placed **horizontally** (left to right **or** righ...
Given a fixed size box, is there a way to quickly query which packages (i.e., count and sizes) should end up in that box size? Do we have to order the boxes a certain way to allow us to answer the query quickly?
Python 3 || 7 lines, with a brief explanation || T/M: 87% / 20%
check-if-word-can-be-placed-in-crossword
0
1
Here\'s the intuition:\n\nThe problem reduces to finding all vertical or horizontal lines of consecutive cells with elements that consist of letters or spaces only and that are the same length as`word`. We can further reduce the problem by only considering whether the rows, left-to-right, allow the word to be placed. W...
4
You are given an `m x n` matrix `board`, representing the **current** state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), `' '` to represent any **empty** cells, and `'#'` to represent any **blocked** cells. A word can be placed **horizontally** (left to right **or** righ...
Given a fixed size box, is there a way to quickly query which packages (i.e., count and sizes) should end up in that box size? Do we have to order the boxes a certain way to allow us to answer the query quickly?
[Python3] row-by-row & col-by-col
check-if-word-can-be-placed-in-crossword
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/fa0bb65b4cb428452e2b4192ad53e56393b8fb8d) for solutions of weekly 260. \n```\nclass Solution:\n def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:\n for x in board, zip(*board): \n for row in x: \n ...
10
You are given an `m x n` matrix `board`, representing the **current** state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), `' '` to represent any **empty** cells, and `'#'` to represent any **blocked** cells. A word can be placed **horizontally** (left to right **or** righ...
Given a fixed size box, is there a way to quickly query which packages (i.e., count and sizes) should end up in that box size? Do we have to order the boxes a certain way to allow us to answer the query quickly?
Python | 2 Methods
check-if-word-can-be-placed-in-crossword
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n1. Just follow the rules and search\n2. transpose the board and perform the match row by row\n\n# Code\n```\nimport itertools\n\nclass Solution:\n\n # method 1: just follow the rules\n def placeWordInCrossword(self, board: List[Li...
0
You are given an `m x n` matrix `board`, representing the **current** state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), `' '` to represent any **empty** cells, and `'#'` to represent any **blocked** cells. A word can be placed **horizontally** (left to right **or** righ...
Given a fixed size box, is there a way to quickly query which packages (i.e., count and sizes) should end up in that box size? Do we have to order the boxes a certain way to allow us to answer the query quickly?
Simple intuitive approach using sets
check-if-word-can-be-placed-in-crossword
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthe words need to fit perfectly between 2 #s or between a # and the end of a row / col or perfectly into a row or col\n# Approach\n<!-- Describe your approach to solving the problem. -->\nStart by finding where are the blocks in the board...
0
You are given an `m x n` matrix `board`, representing the **current** state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), `' '` to represent any **empty** cells, and `'#'` to represent any **blocked** cells. A word can be placed **horizontally** (left to right **or** righ...
Given a fixed size box, is there a way to quickly query which packages (i.e., count and sizes) should end up in that box size? Do we have to order the boxes a certain way to allow us to answer the query quickly?
Index Math [100 % Time]
check-if-word-can-be-placed-in-crossword
0
1
# Approach\nAssume `k` is the length of the word\n\nFor each row, attempt to place horizontally starting from column `c`. For the current row, if both the cells in `(c - 1)th` column and `(c + k)th` column are not either `#` or out of bounds, check the next value of `c`.\nReturn `True` if word or reverse word can be pl...
0
You are given an `m x n` matrix `board`, representing the **current** state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), `' '` to represent any **empty** cells, and `'#'` to represent any **blocked** cells. A word can be placed **horizontally** (left to right **or** righ...
Given a fixed size box, is there a way to quickly query which packages (i.e., count and sizes) should end up in that box size? Do we have to order the boxes a certain way to allow us to answer the query quickly?
[Python3] somewhat dp
the-score-of-students-solving-math-expression
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/fa0bb65b4cb428452e2b4192ad53e56393b8fb8d) for solutions of weekly 260. \n```\nclass Solution:\n def scoreOfStudents(self, s: str, answers: List[int]) -> int:\n \n @cache\n def fn(lo, hi): \n """Return possibl...
6
You are given a string `s` that contains digits `0-9`, addition symbols `'+'`, and multiplication symbols `'*'` **only**, representing a **valid** math expression of **single digit numbers** (e.g., `3+5*2`). This expression was given to `n` elementary school students. The students were instructed to get the answer of t...
Keep track of the indices on both RLE arrays and join the parts together. What is the maximum number of segments if we took the minimum number of elements left on both the current segments every time?
DP with memo
the-score-of-students-solving-math-expression
0
1
# Intuition\n\nOne need to get all possible answers for arithmatically correct computations. To get these you need to split the expression at an operand compute all possible left and right values and combine them with the given opearations. So it is natural to use top down approach here with memoization.\n\n\n# Complex...
0
You are given a string `s` that contains digits `0-9`, addition symbols `'+'`, and multiplication symbols `'*'` **only**, representing a **valid** math expression of **single digit numbers** (e.g., `3+5*2`). This expression was given to `n` elementary school students. The students were instructed to get the answer of t...
Keep track of the indices on both RLE arrays and join the parts together. What is the maximum number of segments if we took the minimum number of elements left on both the current segments every time?
DP with Frequency Domain Reductions
the-score-of-students-solving-math-expression
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is a dp problem. As such, we should look for speedups to make it in under the time complexity limits. One of the most common is a shift to a frequency domain. The first shift is by shifting answers from a list to a map of frequency o...
0
You are given a string `s` that contains digits `0-9`, addition symbols `'+'`, and multiplication symbols `'*'` **only**, representing a **valid** math expression of **single digit numbers** (e.g., `3+5*2`). This expression was given to `n` elementary school students. The students were instructed to get the answer of t...
Keep track of the indices on both RLE arrays and join the parts together. What is the maximum number of segments if we took the minimum number of elements left on both the current segments every time?
Top-down DP solution
the-score-of-students-solving-math-expression
0
1
# Complexity\n- Time complexity: $$O(n^2 \\cdot 2^{n - 1} + m)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n \\cdot n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nwhere `n = s.length`, `m = answers.length`\n\n# Code\n``` python3 []\nclass Solution:\n def score...
0
You are given a string `s` that contains digits `0-9`, addition symbols `'+'`, and multiplication symbols `'*'` **only**, representing a **valid** math expression of **single digit numbers** (e.g., `3+5*2`). This expression was given to `n` elementary school students. The students were instructed to get the answer of t...
Keep track of the indices on both RLE arrays and join the parts together. What is the maximum number of segments if we took the minimum number of elements left on both the current segments every time?
Short DP in Python Faster than 97%
the-score-of-students-solving-math-expression
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing the top-down DP to generate all the possible outcomes in the range of `[0, 1000]`.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nGiven a substring of `s`, we enumerate all possible orders of operators (`+` ...
0
You are given a string `s` that contains digits `0-9`, addition symbols `'+'`, and multiplication symbols `'*'` **only**, representing a **valid** math expression of **single digit numbers** (e.g., `3+5*2`). This expression was given to `n` elementary school students. The students were instructed to get the answer of t...
Keep track of the indices on both RLE arrays and join the parts together. What is the maximum number of segments if we took the minimum number of elements left on both the current segments every time?
My solution...
the-score-of-students-solving-math-expression
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given a string `s` that contains digits `0-9`, addition symbols `'+'`, and multiplication symbols `'*'` **only**, representing a **valid** math expression of **single digit numbers** (e.g., `3+5*2`). This expression was given to `n` elementary school students. The students were instructed to get the answer of t...
Keep track of the indices on both RLE arrays and join the parts together. What is the maximum number of segments if we took the minimum number of elements left on both the current segments every time?
Top-down DP, short & clean
the-score-of-students-solving-math-expression
0
1
# Intuition\nSo main challenge is to calculate all possible outcomes (e.g. any valid `(...)` expression). So let\'s decompose what does that mean\nLet `f(l,r)` be the set of all possible outcomes of `s[l:r]` (assuming it stars and ends withs a digit). Then all possibilities could be defined as trying to chose any opera...
0
You are given a string `s` that contains digits `0-9`, addition symbols `'+'`, and multiplication symbols `'*'` **only**, representing a **valid** math expression of **single digit numbers** (e.g., `3+5*2`). This expression was given to `n` elementary school students. The students were instructed to get the answer of t...
Keep track of the indices on both RLE arrays and join the parts together. What is the maximum number of segments if we took the minimum number of elements left on both the current segments every time?
Python Easy Solution
convert-1d-array-into-2d-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)$$ --...
5
You are given a **0-indexed** 1-dimensional (1D) integer array `original`, and two integers, `m` and `n`. You are tasked with creating a 2-dimensional (2D) array with `m` rows and `n` columns using **all** the elements from `original`. The elements from indices `0` to `n - 1` (**inclusive**) of `original` should form ...
Is only tracking a single sum enough to solve the problem? How does tracking an odd sum and an even sum reduce the number of states?
Python Easy Solution
convert-1d-array-into-2d-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** 1-dimensional (1D) integer array `original`, and two integers, `m` and `n`. You are tasked with creating a 2-dimensional (2D) array with `m` rows and `n` columns using **all** the elements from `original`. The elements from indices `0` to `n - 1` (**inclusive**) of `original` should form ...
Is only tracking a single sum enough to solve the problem? How does tracking an odd sum and an even sum reduce the number of states?
6 Lines Of Code-->Powerful Math Approach
convert-1d-array-into-2d-array
0
1
\n\n# 1. Math Approach\n```\nclass Solution:\n def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:\n if len(original)!=m*n:\n return []\n matrix=[]\n for i in range(0,len(original),n):\n matrix.append(original[i:i+n])\n return matrix\n...
2
You are given a **0-indexed** 1-dimensional (1D) integer array `original`, and two integers, `m` and `n`. You are tasked with creating a 2-dimensional (2D) array with `m` rows and `n` columns using **all** the elements from `original`. The elements from indices `0` to `n - 1` (**inclusive**) of `original` should form ...
Is only tracking a single sum enough to solve the problem? How does tracking an odd sum and an even sum reduce the number of states?
[Python3] simulation
convert-1d-array-into-2d-array
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/182350e41572fb26ffb8c44204b037cc9f0e5035) for solutions of biweekly 62. \n```\nclass Solution:\n def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:\n ans = []\n if len(original) == m*n: \n ...
42
You are given a **0-indexed** 1-dimensional (1D) integer array `original`, and two integers, `m` and `n`. You are tasked with creating a 2-dimensional (2D) array with `m` rows and `n` columns using **all** the elements from `original`. The elements from indices `0` to `n - 1` (**inclusive**) of `original` should form ...
Is only tracking a single sum enough to solve the problem? How does tracking an odd sum and an even sum reduce the number of states?
Python one line
convert-1d-array-into-2d-array
0
1
One line:\n```\nclass Solution:\n def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:\n return [original[i:i+n] for i in range(0, len(original), n)] if m*n == len(original) else []\n \n```\n\nWhich is equivalent to\n```\nclass Solution:\n def construct2DArray(self, or...
16
You are given a **0-indexed** 1-dimensional (1D) integer array `original`, and two integers, `m` and `n`. You are tasked with creating a 2-dimensional (2D) array with `m` rows and `n` columns using **all** the elements from `original`. The elements from indices `0` to `n - 1` (**inclusive**) of `original` should form ...
Is only tracking a single sum enough to solve the problem? How does tracking an odd sum and an even sum reduce the number of states?
Noob Code : Easy to Understand
number-of-pairs-of-strings-with-concatenation-equal-to-target
0
1
![image.png](https://assets.leetcode.com/users/images/87cbfdb7-580b-4159-8261-224ea78e98cf_1696273237.9498467.png)\n\n\n# Approach\n1. Initialize a counter variable `c` to 0. This variable will be used to keep track of the count of valid pairs.\n\n2. Create a copy of the `nums` list and store it in the `l` variable. Th...
1
Given an array of **digit** strings `nums` and a **digit** string `target`, return _the number of pairs of indices_ `(i, j)` _(where_ `i != j`_) such that the **concatenation** of_ `nums[i] + nums[j]` _equals_ `target`. **Example 1:** **Input:** nums = \[ "777 ", "7 ", "77 ", "77 "\], target = "7777 " **Output:** 4 ...
You need to maintain a sorted list for each movie and a sorted list for rented movies When renting a movie remove it from its movies sorted list and added it to the rented list and vice versa in the case of dropping a movie
Dictionary & List || Python
number-of-pairs-of-strings-with-concatenation-equal-to-target
0
1
# Code\n```\nclass Solution:\n def numOfPairs(self, nums: List[str], target: str) -> int:\n d = defaultdict(int)\n for char in nums:\n d[char] += 1\n \n arr = []\n for char in target:\n arr.append(char)\n \n pairs = 0\n num = ""\n ...
1
Given an array of **digit** strings `nums` and a **digit** string `target`, return _the number of pairs of indices_ `(i, j)` _(where_ `i != j`_) such that the **concatenation** of_ `nums[i] + nums[j]` _equals_ `target`. **Example 1:** **Input:** nums = \[ "777 ", "7 ", "77 ", "77 "\], target = "7777 " **Output:** 4 ...
You need to maintain a sorted list for each movie and a sorted list for rented movies When renting a movie remove it from its movies sorted list and added it to the rented list and vice versa in the case of dropping a movie
[Java/Python 3] One pass O(NM) HashTable codes w/ analysis.
number-of-pairs-of-strings-with-concatenation-equal-to-target
1
1
```java\n public int numOfPairs(String[] nums, String target) {\n int cnt = 0, n = target.length();\n Map<Integer, Integer> prefix = new HashMap<>(), suffix = new HashMap<>();\n for (String num : nums) {\n int sz = num.length();\n if (target.startsWith(num)) {\n ...
20
Given an array of **digit** strings `nums` and a **digit** string `target`, return _the number of pairs of indices_ `(i, j)` _(where_ `i != j`_) such that the **concatenation** of_ `nums[i] + nums[j]` _equals_ `target`. **Example 1:** **Input:** nums = \[ "777 ", "7 ", "77 ", "77 "\], target = "7777 " **Output:** 4 ...
You need to maintain a sorted list for each movie and a sorted list for rented movies When renting a movie remove it from its movies sorted list and added it to the rented list and vice versa in the case of dropping a movie
[Python3] freq table
number-of-pairs-of-strings-with-concatenation-equal-to-target
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/182350e41572fb26ffb8c44204b037cc9f0e5035) for solutions of biweekly 62. \n```\nclass Solution:\n def numOfPairs(self, nums: List[str], target: str) -> int:\n freq = Counter(nums)\n ans = 0 \n for k, v in freq.items(): \...
45
Given an array of **digit** strings `nums` and a **digit** string `target`, return _the number of pairs of indices_ `(i, j)` _(where_ `i != j`_) such that the **concatenation** of_ `nums[i] + nums[j]` _equals_ `target`. **Example 1:** **Input:** nums = \[ "777 ", "7 ", "77 ", "77 "\], target = "7777 " **Output:** 4 ...
You need to maintain a sorted list for each movie and a sorted list for rented movies When renting a movie remove it from its movies sorted list and added it to the rented list and vice versa in the case of dropping a movie
python3 Solution
number-of-pairs-of-strings-with-concatenation-equal-to-target
0
1
\n```\nclass Solution:\n def numOfPairs(self,nums:List[str],target:str)->int:\n n=len(nums)\n count=0\n for i in range(n):\n for j in range(n):\n if i!=j:\n if nums[i]+nums[j]==target:\n count+=1\n\n return count ...
1
Given an array of **digit** strings `nums` and a **digit** string `target`, return _the number of pairs of indices_ `(i, j)` _(where_ `i != j`_) such that the **concatenation** of_ `nums[i] + nums[j]` _equals_ `target`. **Example 1:** **Input:** nums = \[ "777 ", "7 ", "77 ", "77 "\], target = "7777 " **Output:** 4 ...
You need to maintain a sorted list for each movie and a sorted list for rented movies When renting a movie remove it from its movies sorted list and added it to the rented list and vice versa in the case of dropping a movie
Python3|| Beats 94.22%
number-of-pairs-of-strings-with-concatenation-equal-to-target
0
1
# Please upvote guys!\n![image.png](https://assets.leetcode.com/users/images/cb2e81c1-3396-47c7-9f61-9ec23de46dee_1679162142.8444855.png)\n\n# Code\n```\nclass Solution:\n def numOfPairs(self, nums: List[str], target: str) -> int:\n count=0\n for i in range(len(nums)):\n for j in range(len(n...
2
Given an array of **digit** strings `nums` and a **digit** string `target`, return _the number of pairs of indices_ `(i, j)` _(where_ `i != j`_) such that the **concatenation** of_ `nums[i] + nums[j]` _equals_ `target`. **Example 1:** **Input:** nums = \[ "777 ", "7 ", "77 ", "77 "\], target = "7777 " **Output:** 4 ...
You need to maintain a sorted list for each movie and a sorted list for rented movies When renting a movie remove it from its movies sorted list and added it to the rented list and vice versa in the case of dropping a movie
[Python 3] Simple one-liner using permutations() | Straightforward
number-of-pairs-of-strings-with-concatenation-equal-to-target
0
1
```\nclass Solution:\n def numOfPairs(self, nums, target):\n return sum(i + j == target for i, j in permutations(nums, 2))\n```
5
Given an array of **digit** strings `nums` and a **digit** string `target`, return _the number of pairs of indices_ `(i, j)` _(where_ `i != j`_) such that the **concatenation** of_ `nums[i] + nums[j]` _equals_ `target`. **Example 1:** **Input:** nums = \[ "777 ", "7 ", "77 ", "77 "\], target = "7777 " **Output:** 4 ...
You need to maintain a sorted list for each movie and a sorted list for rented movies When renting a movie remove it from its movies sorted list and added it to the rented list and vice versa in the case of dropping a movie
Beste Easy Solution Bruteforce
number-of-pairs-of-strings-with-concatenation-equal-to-target
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nIterate And Slicing\n\n# Complexity\n- Time complexity:\nO(N^2)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def numOfPairs(self, nums: List[str], target: str) -> int:\n c=0\n for i in rang...
1
Given an array of **digit** strings `nums` and a **digit** string `target`, return _the number of pairs of indices_ `(i, j)` _(where_ `i != j`_) such that the **concatenation** of_ `nums[i] + nums[j]` _equals_ `target`. **Example 1:** **Input:** nums = \[ "777 ", "7 ", "77 ", "77 "\], target = "7777 " **Output:** 4 ...
You need to maintain a sorted list for each movie and a sorted list for rented movies When renting a movie remove it from its movies sorted list and added it to the rented list and vice versa in the case of dropping a movie
Python easy solution using collections
maximize-the-confusion-of-an-exam
0
1
\n# Code\n```\nimport collections\n\nclass Solution:\n def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:\n\n max_freq = i = 0\n char_count = collections.Counter()\n\n for j in range(len(answerKey)):\n char_count[answerKey[j]] += 1\n max_freq = max(max_freq, ch...
1
A teacher is writing a test with `n` true/false questions, with `'T'` denoting true and `'F'` denoting false. He wants to confuse the students by **maximizing** the number of **consecutive** questions with the **same** answer (multiple trues or multiple falses in a row). You are given a string `answerKey`, where `answ...
null
Simple Python || O(N) || Concise || Two Pointers ✅✅
maximize-the-confusion-of-an-exam
0
1
# Approach\n> Calculating the minimum of the number of `T`s and `F`s. And, Trying to keep it smaller than `K`.\n\n> If it is greater than `K`, the size of the window is decreased.\nHere, the sliding window starts at `i` and ends at `j-1`\n# Code\n```\nclass Solution:\n def maxConsecutiveAnswers(self, answerKey: str,...
1
A teacher is writing a test with `n` true/false questions, with `'T'` denoting true and `'F'` denoting false. He wants to confuse the students by **maximizing** the number of **consecutive** questions with the **same** answer (multiple trues or multiple falses in a row). You are given a string `answerKey`, where `answ...
null
[Python3] Counter of (Left - Right) at Each Pivot
maximum-number-of-ways-to-partition-an-array
0
1
```python\nclass Solution:\n def waysToPartition(self, nums: List[int], k: int) -> int:\n """This is a good problem. It\'s not difficult, but is quite complex.\n\n The idea is that once we change a position at i, for all the pivots at\n 1...i, the sum of the left half stay the same whereas the s...
1
You are given a **0-indexed** integer array `nums` of length `n`. The number of ways to **partition** `nums` is the number of `pivot` indices that satisfy both conditions: * `1 <= pivot < n` * `nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]` You are also given an in...
Characters are independent—only the frequency of characters matters. It is possible to distribute characters if all characters can be divided equally among all strings.
78% TC and 56% SC easy python solution
maximum-number-of-ways-to-partition-an-array
0
1
1. Create a map of list , going thru the indices and make diff between right half and left half as key.\n2. Store all the indices in the list having the diff as x, as you gonna need it it later.\n3. Now try to change all the indices and check how many indices could now become your pivot.\n4. So you are changing a num, ...
2
You are given a **0-indexed** integer array `nums` of length `n`. The number of ways to **partition** `nums` is the number of `pivot` indices that satisfy both conditions: * `1 <= pivot < n` * `nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]` You are also given an in...
Characters are independent—only the frequency of characters matters. It is possible to distribute characters if all characters can be divided equally among all strings.
Prefix Sum + 2 hash tables in python3
maximum-number-of-ways-to-partition-an-array
0
1
\n\n# Code\n```\nclass Solution:\n def waysToPartition(self, nums: List[int], k: int) -> int:\n s = sum(nums)\n n = len(nums)\n prefix = []\n suffix = []\n currsum = 0\n diff = {}\n for i,a in enumerate(nums[:-1]):\n currsum += a\n prefix.append(...
0
You are given a **0-indexed** integer array `nums` of length `n`. The number of ways to **partition** `nums` is the number of `pivot` indices that satisfy both conditions: * `1 <= pivot < n` * `nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]` You are also given an in...
Characters are independent—only the frequency of characters matters. It is possible to distribute characters if all characters can be divided equally among all strings.
[Python3] binary search
maximum-number-of-ways-to-partition-an-array
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/182350e41572fb26ffb8c44204b037cc9f0e5035) for solutions of biweekly 62. \n```\nclass Solution:\n def waysToPartition(self, nums: List[int], k: int) -> int:\n prefix = [0]\n loc = defaultdict(list)\n for i, x in enumerat...
2
You are given a **0-indexed** integer array `nums` of length `n`. The number of ways to **partition** `nums` is the number of `pivot` indices that satisfy both conditions: * `1 <= pivot < n` * `nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]` You are also given an in...
Characters are independent—only the frequency of characters matters. It is possible to distribute characters if all characters can be divided equally among all strings.
Python3 Neat Code
minimum-moves-to-convert-string
0
1
# Code\n```\nclass Solution:\n def minimumMoves(self, s: str) -> int:\n ans=i=0\n while i<len(s):\n if s[i]==\'O\':i+=1\n else:\n i+=3\n ans+=1\n return ans\n```
1
You are given a string `s` consisting of `n` characters which are either `'X'` or `'O'`. A **move** is defined as selecting **three** **consecutive characters** of `s` and converting them to `'O'`. Note that if a move is applied to the character `'O'`, it will stay the **same**. Return _the **minimum** number of move...
First, we need to think about solving an easier problem, If we remove a set of indices from the string does P exist in S as a subsequence We can binary search the K and check by solving the above problem.
[Python3] scan
minimum-moves-to-convert-string
0
1
\n```\nclass Solution:\n def minimumMoves(self, s: str) -> int:\n ans = i = 0\n while i < len(s): \n if s[i] == "X": \n ans += 1\n i += 3\n else: i += 1\n return ans \n```
35
You are given a string `s` consisting of `n` characters which are either `'X'` or `'O'`. A **move** is defined as selecting **three** **consecutive characters** of `s` and converting them to `'O'`. Note that if a move is applied to the character `'O'`, it will stay the **same**. Return _the **minimum** number of move...
First, we need to think about solving an easier problem, If we remove a set of indices from the string does P exist in S as a subsequence We can binary search the K and check by solving the above problem.
✅ 99% beats || Python3 || While loop
minimum-moves-to-convert-string
0
1
# Intuition\n![Screenshot from 2023-10-18 14-41-08.png](https://assets.leetcode.com/users/images/037b7735-243f-4693-b292-f01d5443e4a3_1697622117.6472003.png)\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\n Use while.\n\n 1.Assign i pointer to while loop as given word`s index...
1
You are given a string `s` consisting of `n` characters which are either `'X'` or `'O'`. A **move** is defined as selecting **three** **consecutive characters** of `s` and converting them to `'O'`. Note that if a move is applied to the character `'O'`, it will stay the **same**. Return _the **minimum** number of move...
First, we need to think about solving an easier problem, If we remove a set of indices from the string does P exist in S as a subsequence We can binary search the K and check by solving the above problem.
2027. Run time - 95.42% | Memory - 87%
minimum-moves-to-convert-string
0
1
# Code\n```\nclass Solution:\n def minimumMoves(self, s: str) -> int:\n ind, moves = 0, 0\n n = len(s)\n while ind < n:\n if s[ind] == \'X\':\n ind += 3\n moves += 1\n else:\n ind += 1\n return moves\n\n```
2
You are given a string `s` consisting of `n` characters which are either `'X'` or `'O'`. A **move** is defined as selecting **three** **consecutive characters** of `s` and converting them to `'O'`. Note that if a move is applied to the character `'O'`, it will stay the **same**. Return _the **minimum** number of move...
First, we need to think about solving an easier problem, If we remove a set of indices from the string does P exist in S as a subsequence We can binary search the K and check by solving the above problem.
Easy Python Solution | Faster than 99% (24 ms)
minimum-moves-to-convert-string
0
1
# Easy Python Solution | Faster than 99% (24 ms)\n**Runtime: 24 ms, faster than 99% of Python3 online submissions for Minimum Moves to Convert String.\nMemory Usage: 14.2 MB.**\n\n```\nclass Solution:\n def minimumMoves(self, s: str) -> int:\n i, m = 0, 0\n l = len(s)\n\n while i < l:\n ...
6
You are given a string `s` consisting of `n` characters which are either `'X'` or `'O'`. A **move** is defined as selecting **three** **consecutive characters** of `s` and converting them to `'O'`. Note that if a move is applied to the character `'O'`, it will stay the **same**. Return _the **minimum** number of move...
First, we need to think about solving an easier problem, If we remove a set of indices from the string does P exist in S as a subsequence We can binary search the K and check by solving the above problem.
Python fast and simple solution
minimum-moves-to-convert-string
0
1
\n# Code\n```\nclass Solution:\n def minimumMoves(self, s: str) -> int:\n count = 0\n last = None\n for index,item in enumerate(s):\n if item == \'X\' and (last == None or abs(last - index) > 2):\n last = index\n count +=1 \n \n return count\n``...
0
You are given a string `s` consisting of `n` characters which are either `'X'` or `'O'`. A **move** is defined as selecting **three** **consecutive characters** of `s` and converting them to `'O'`. Note that if a move is applied to the character `'O'`, it will stay the **same**. Return _the **minimum** number of move...
First, we need to think about solving an easier problem, If we remove a set of indices from the string does P exist in S as a subsequence We can binary search the K and check by solving the above problem.
Simple solutions for begineer
minimum-moves-to-convert-string
0
1
# Code\n```\nclass Solution:\n def minimumMoves(self, s: str) -> int:\n # bruteforce solutions\n # 33ms\n # Beats 88.92% of users with Python3\n """\n ret, l = 0, 0\n while l < len(s):\n if s[l] == "X":\n if l+3 > len(s):\n s = s[...
0
You are given a string `s` consisting of `n` characters which are either `'X'` or `'O'`. A **move** is defined as selecting **three** **consecutive characters** of `s` and converting them to `'O'`. Note that if a move is applied to the character `'O'`, it will stay the **same**. Return _the **minimum** number of move...
First, we need to think about solving an easier problem, If we remove a set of indices from the string does P exist in S as a subsequence We can binary search the K and check by solving the above problem.
Not easy but works
minimum-moves-to-convert-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given a string `s` consisting of `n` characters which are either `'X'` or `'O'`. A **move** is defined as selecting **three** **consecutive characters** of `s` and converting them to `'O'`. Note that if a move is applied to the character `'O'`, it will stay the **same**. Return _the **minimum** number of move...
First, we need to think about solving an easier problem, If we remove a set of indices from the string does P exist in S as a subsequence We can binary search the K and check by solving the above problem.
Python Easy Solution || Logic
find-missing-observations
0
1
# Code\n```\nclass Solution:\n def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:\n curSum=sum(rolls)\n obv=n+len(rolls)\n missSum=mean*obv-curSum\n if missSum>6*n or missSum<0 or missSum<n:\n return []\n x=missSum//n\n res=[x]*n\n re...
1
You have observations of `n + m` **6-sided** dice rolls with each face numbered from `1` to `6`. `n` of the observations went missing, and you only have the observations of `m` rolls. Fortunately, you have also calculated the **average value** of the `n + m` rolls. You are given an integer array `rolls` of length `m` ...
Brute force using bitmasks and simulate the rounds. Calculate each state one time and save its solution.
Easy to Understand || 72% || Python3
find-missing-observations
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, ...
2
You have observations of `n + m` **6-sided** dice rolls with each face numbered from `1` to `6`. `n` of the observations went missing, and you only have the observations of `m` rolls. Fortunately, you have also calculated the **average value** of the `n + m` rolls. You are given an integer array `rolls` of length `m` ...
Brute force using bitmasks and simulate the rounds. Calculate each state one time and save its solution.
O(m+n) time | O(n) space | solution explained
find-missing-observations
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFind the sum of missing n rolls\n*missing sum = target sum - sum of m rolls = mean * (m + n) - sum of m rolls*\n\nCheck if the missing sum can be distributed to n rolls. If yes, find the average *(missing sum / n)* and distribute it. Dist...
2
You have observations of `n + m` **6-sided** dice rolls with each face numbered from `1` to `6`. `n` of the observations went missing, and you only have the observations of `m` rolls. Fortunately, you have also calculated the **average value** of the `n + m` rolls. You are given an integer array `rolls` of length `m` ...
Brute force using bitmasks and simulate the rounds. Calculate each state one time and save its solution.
beats 97% easy to understand
find-missing-observations
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nfirst calculate if the sum is achevable, then calculate the dice value by average and modulos\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e....
0
You have observations of `n + m` **6-sided** dice rolls with each face numbered from `1` to `6`. `n` of the observations went missing, and you only have the observations of `m` rolls. Fortunately, you have also calculated the **average value** of the `n + m` rolls. You are given an integer array `rolls` of length `m` ...
Brute force using bitmasks and simulate the rounds. Calculate each state one time and save its solution.
Python beats 95% 1 loop subtract from sum as you go
find-missing-observations
0
1
```\nclass Solution:\n def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:\n #rolls has the m rolls\n #mean is the mean of m + n rolls\n #n is the len of missing rolls\n #return all n rolls\n #sum_m = sum(rolls)\n #sum_n = (mean*n)\n #mean = sum ...
0
You have observations of `n + m` **6-sided** dice rolls with each face numbered from `1` to `6`. `n` of the observations went missing, and you only have the observations of `m` rolls. Fortunately, you have also calculated the **average value** of the `n + m` rolls. You are given an integer array `rolls` of length `m` ...
Brute force using bitmasks and simulate the rounds. Calculate each state one time and save its solution.
Fastest Python solution. Beat 100%
find-missing-observations
0
1
# Intuition\nFirst check if the problem is solvable by calculating the max. and min. change in mean possible. Then calculate the missing sum and the dice throws within that.\n\n# Approach\nSince the programm is supposed to run as fast as possible, it makes sense to first calculate if the problem has a solution at all. ...
0
You have observations of `n + m` **6-sided** dice rolls with each face numbered from `1` to `6`. `n` of the observations went missing, and you only have the observations of `m` rolls. Fortunately, you have also calculated the **average value** of the `n + m` rolls. You are given an integer array `rolls` of length `m` ...
Brute force using bitmasks and simulate the rounds. Calculate each state one time and save its solution.
O(N) solution beats 100%
find-missing-observations
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)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n...
0
You have observations of `n + m` **6-sided** dice rolls with each face numbered from `1` to `6`. `n` of the observations went missing, and you only have the observations of `m` rolls. Fortunately, you have also calculated the **average value** of the `n + m` rolls. You are given an integer array `rolls` of length `m` ...
Brute force using bitmasks and simulate the rounds. Calculate each state one time and save its solution.
Python Simple Solution | 90% | 4 lines
find-missing-observations
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nFind the target sum of the unknown observations by using the average calculation. Ensure the target sum is reachable by checking targetSum > n (roll 1 each time) and targetSum < 6*n (roll 6 each time).\n\nThen, it\'s simply a matter of finding a combi...
0
You have observations of `n + m` **6-sided** dice rolls with each face numbered from `1` to `6`. `n` of the observations went missing, and you only have the observations of `m` rolls. Fortunately, you have also calculated the **average value** of the `n + m` rolls. You are given an integer array `rolls` of length `m` ...
Brute force using bitmasks and simulate the rounds. Calculate each state one time and save its solution.
[Python3] freq table
stone-game-ix
0
1
**Intuition**\nHere, the specific numbers don\'t matter. Only the modulos do. \nIn order for Alice to win, the sequence would be like \n1) 1(12)(12)...(12)2 with even number of 0\'s between first 1 and final 2\n2) 1(12)(12)...(12)11 with odd number of 0\'s between first 1 and final 1\n\nwhere 1\'s and 2\'s are intercha...
4
Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array `stones`, where `stones[i]` is the **value** of the `ith` stone. Alice and Bob take turns, with **Alice** starting first. On each turn, the player may remove any stone from...
Is there a particular way we should order the arrays such that the product sum is minimized? Would you want to multiply two numbers that are closer to one another or further?
python clean and short solution
stone-game-ix
0
1
```\nclass Solution:\n def stoneGameIX(self, stones: List[int]) -> bool:\n stones = [v % 3 for v in stones]\n \n d = defaultdict(int)\n for v in stones:\n d[v] += 1\n \n while d[1] >= 2 and d[2] >= 2:\n d[2] -= 1\n d[1] -= 1\n \n ...
1
Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array `stones`, where `stones[i]` is the **value** of the `ith` stone. Alice and Bob take turns, with **Alice** starting first. On each turn, the player may remove any stone from...
Is there a particular way we should order the arrays such that the product sum is minimized? Would you want to multiply two numbers that are closer to one another or further?
Monotonic Stack
smallest-k-length-subsequence-with-occurrences-of-a-letter
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBased on the increasing monotonic stack, keep the smallest letter in the stack.\nFor this problem, require the specified letters for repetition times.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nstack pop:\nwhe...
0
You are given a string `s`, an integer `k`, a letter `letter`, and an integer `repetition`. Return _the **lexicographically smallest** subsequence of_ `s` _of length_ `k` _that has the letter_ `letter` _appear **at least**_ `repetition` _times_. The test cases are generated so that the `letter` appears in `s` **at lea...
null
Python Heap based solution
smallest-k-length-subsequence-with-occurrences-of-a-letter
0
1
# Complexity\n- Time complexity:\n$$O(N * log(N))$$\n\n- Space complexity:\n$$O(N)$$\n\n# Code\n```\nclass Solution:\n def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str:\n suffix_count = [0 for _ in range(len(s) + 1)]\n\n for i in range(len(s) - 1, -1, -1):\n ...
0
You are given a string `s`, an integer `k`, a letter `letter`, and an integer `repetition`. Return _the **lexicographically smallest** subsequence of_ `s` _of length_ `k` _that has the letter_ `letter` _appear **at least**_ `repetition` _times_. The test cases are generated so that the `letter` appears in `s` **at lea...
null
Python (Simple Stack Solution)
smallest-k-length-subsequence-with-occurrences-of-a-letter
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`, an integer `k`, a letter `letter`, and an integer `repetition`. Return _the **lexicographically smallest** subsequence of_ `s` _of length_ `k` _that has the letter_ `letter` _appear **at least**_ `repetition` _times_. The test cases are generated so that the `letter` appears in `s` **at lea...
null
[PYTHON3] O(n) using stack with explanation
smallest-k-length-subsequence-with-occurrences-of-a-letter
0
1
First, we need to count how many time `letter` occurs in the whole string.\nNext, we enumerate and keep track of how many times `letter` occurred (and how many are remaining) and greedily add the current character with some condition. \n\nIf we need to remove the top element of the stack, we need to have these three co...
2
You are given a string `s`, an integer `k`, a letter `letter`, and an integer `repetition`. Return _the **lexicographically smallest** subsequence of_ `s` _of length_ `k` _that has the letter_ `letter` _appear **at least**_ `repetition` _times_. The test cases are generated so that the `letter` appears in `s` **at lea...
null
Python Stack solution
smallest-k-length-subsequence-with-occurrences-of-a-letter
0
1
```\nclass Solution:\n def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str:\n s = list(s)\n stack = []\n countAll = s.count(letter)\n count = 0\n for ind, i in enumerate(s):\n while stack and stack[-1] > i:\n if stack[-1] == ...
1
You are given a string `s`, an integer `k`, a letter `letter`, and an integer `repetition`. Return _the **lexicographically smallest** subsequence of_ `s` _of length_ `k` _that has the letter_ `letter` _appear **at least**_ `repetition` _times_. The test cases are generated so that the `letter` appears in `s` **at lea...
null
Counter Python solution
two-out-of-three
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Given three integer arrays `nums1`, `nums2`, and `nums3`, return _a **distinct** array containing all the values that are present in **at least two** out of the three arrays. You may return the values in **any** order_. **Example 1:** **Input:** nums1 = \[1,1,3,2\], nums2 = \[2,3\], nums3 = \[3\] **Output:** \[3,2\] ...
In what order should you iterate through the digits? If an odd number exists, where must the number start from?
python easy solution !
two-out-of-three
0
1
# Intuition\n # Iterate through the combined iterable of all three arrays and find values that are present in at least two arrays.\n \n\n\n# Approach\n\n \n \n # - Combine all three arrays into a single iterable.\n # - For each value in the combined iterable, check if it is prese...
4
Given three integer arrays `nums1`, `nums2`, and `nums3`, return _a **distinct** array containing all the values that are present in **at least two** out of the three arrays. You may return the values in **any** order_. **Example 1:** **Input:** nums1 = \[1,1,3,2\], nums2 = \[2,3\], nums3 = \[3\] **Output:** \[3,2\] ...
In what order should you iterate through the digits? If an odd number exists, where must the number start from?
Python one line simple solution
two-out-of-three
0
1
**Python :**\n\n```\ndef twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:\n\treturn set(nums1) & set(nums2) | set(nums2) & set(nums3) | set(nums1) & set(nums3)\n```\n\n**Like it ? please upvote !**
67
Given three integer arrays `nums1`, `nums2`, and `nums3`, return _a **distinct** array containing all the values that are present in **at least two** out of the three arrays. You may return the values in **any** order_. **Example 1:** **Input:** nums1 = \[1,1,3,2\], nums2 = \[2,3\], nums3 = \[3\] **Output:** \[3,2\] ...
In what order should you iterate through the digits? If an odd number exists, where must the number start from?
🔥100% EASY TO UNDERSTAND/SIMPLE/CLEAN🔥
two-out-of-three
0
1
```\nclass Solution:\n def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:\n output = []\n for i in nums1:\n if i in nums2 or i in nums3:\n if i not in output:\n output.append(i)\n for j in nums2:\n i...
0
Given three integer arrays `nums1`, `nums2`, and `nums3`, return _a **distinct** array containing all the values that are present in **at least two** out of the three arrays. You may return the values in **any** order_. **Example 1:** **Input:** nums1 = \[1,1,3,2\], nums2 = \[2,3\], nums3 = \[3\] **Output:** \[3,2\] ...
In what order should you iterate through the digits? If an odd number exists, where must the number start from?
[Python3] set
two-out-of-three
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/933e9b50b2532374ab8252f431da84b6675663a8) for solutions of weekly 262.\n```\nclass Solution:\n def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:\n s1, s2, s3 = set(nums1), set(nums2), set(num...
26
Given three integer arrays `nums1`, `nums2`, and `nums3`, return _a **distinct** array containing all the values that are present in **at least two** out of the three arrays. You may return the values in **any** order_. **Example 1:** **Input:** nums1 = \[1,1,3,2\], nums2 = \[2,3\], nums3 = \[3\] **Output:** \[3,2\] ...
In what order should you iterate through the digits? If an odd number exists, where must the number start from?
Easy Python Solution | Faster than 97% (64 ms)
two-out-of-three
0
1
# Easy Python Solution | Faster than 97% (64 ms)\n**Runtime: 64 ms, faster than 97% of Python3 online submissions for Two Out of Three.\nMemory Usage: 14.2 MB.**\n\n```\nclass Solution:\n def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:\n ret = []\n\n ret += s...
7
Given three integer arrays `nums1`, `nums2`, and `nums3`, return _a **distinct** array containing all the values that are present in **at least two** out of the three arrays. You may return the values in **any** order_. **Example 1:** **Input:** nums1 = \[1,1,3,2\], nums2 = \[2,3\], nums3 = \[3\] **Output:** \[3,2\] ...
In what order should you iterate through the digits? If an odd number exists, where must the number start from?
PYTHON | Simple python solution
two-out-of-three
0
1
```\nclass Solution:\n def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:\n countMap = {}\n \n for i in set(nums1):\n countMap[i] = 1 + countMap.get(i, 0)\n \n for i in set(nums2):\n countMap[i] = 1 + countMap.get(i, 0)...
2
Given three integer arrays `nums1`, `nums2`, and `nums3`, return _a **distinct** array containing all the values that are present in **at least two** out of the three arrays. You may return the values in **any** order_. **Example 1:** **Input:** nums1 = \[1,1,3,2\], nums2 = \[2,3\], nums3 = \[3\] **Output:** \[3,2\] ...
In what order should you iterate through the digits? If an odd number exists, where must the number start from?
[Python3] median 4-line
minimum-operations-to-make-a-uni-value-grid
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/933e9b50b2532374ab8252f431da84b6675663a8) for solutions of weekly 262.\n```\nclass Solution:\n def minOperations(self, grid: List[List[int]], x: int) -> int:\n vals = [x for row in grid for x in row]\n if len(set(val%x for val...
22
You are given a 2D integer `grid` of size `m x n` and an integer `x`. In one operation, you can **add** `x` to or **subtract** `x` from any element in the `grid`. A **uni-value grid** is a grid where all the elements of it are equal. Return _the **minimum** number of operations to make the grid **uni-value**_. If it ...
Consider the day as 48 hours instead of 24. For each round check if you were playing.
[Python3] Why median is optimal | Detailed Explanation
minimum-operations-to-make-a-uni-value-grid
0
1
So I have seen a few posts showing the code but none of them go to the mathematical detail of this problem.\nHere\'s my attempt at explaining this problem and how the solution is derived.\n\nPoints to note:\n1. We dont really care about the matrix itself. We just want the values, so we can just safely ignore the matrix...
5
You are given a 2D integer `grid` of size `m x n` and an integer `x`. In one operation, you can **add** `x` to or **subtract** `x` from any element in the `grid`. A **uni-value grid** is a grid where all the elements of it are equal. Return _the **minimum** number of operations to make the grid **uni-value**_. If it ...
Consider the day as 48 hours instead of 24. For each round check if you were playing.
Numpy 4-liner beats 100% in speed
minimum-operations-to-make-a-uni-value-grid
0
1
# Intuition\nPython is slow, numpy delegates some operations to internal C implementation, which is way faster\n\n# Approach\nJust use numpy\n\n# Complexity\n- Time complexity: $O(n)$\nmultiple operasions that traverses whole matrix\n\n- Space complexity: $O(n)$\nConversion to numpy array traverses whole matrix\n\n$n$ ...
0
You are given a 2D integer `grid` of size `m x n` and an integer `x`. In one operation, you can **add** `x` to or **subtract** `x` from any element in the `grid`. A **uni-value grid** is a grid where all the elements of it are equal. Return _the **minimum** number of operations to make the grid **uni-value**_. If it ...
Consider the day as 48 hours instead of 24. For each round check if you were playing.
Ternary Search
minimum-operations-to-make-a-uni-value-grid
0
1
# Approach\nThe grid can be made uni-value if each value of the grid mod x is uni-value. We can use a set to detect that.\n\nThe function f defines the number of operations to shift all value to k.\nSince f is unimodal, we could utilize ternary search shrink interval [min, max] small enough and then brute force it.\n ...
0
You are given a 2D integer `grid` of size `m x n` and an integer `x`. In one operation, you can **add** `x` to or **subtract** `x` from any element in the `grid`. A **uni-value grid** is a grid where all the elements of it are equal. Return _the **minimum** number of operations to make the grid **uni-value**_. If it ...
Consider the day as 48 hours instead of 24. For each round check if you were playing.
[Python3] hash map & 2 heaps
stock-price-fluctuation
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/933e9b50b2532374ab8252f431da84b6675663a8) for solutions of weekly 262.\n```\nclass StockPrice:\n\n def __init__(self):\n self.mp = {}\n self.maxp = [] # max-heap \n self.minp = [] # min-heap \n self.latest = 0 # ...
41
You are given a stream of **records** about a particular stock. Each record contains a **timestamp** and the corresponding **price** of the stock at that timestamp. Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record ...
How does the maximum value being 100 help us? How can we tell if a number exists in a given range?
Python | Easy Explanation | Meet in the Middle
partition-array-into-two-arrays-to-minimize-sum-difference
0
1
**NOTE** - This is question was very easy, if you had done this https://leetcode.com/problems/closest-subsequence-sum/. So Please first go and try that.\n\nHere we have to find 2 groups of equal length (N).\nLet\'s say, left_ans is required the N elements required for first group, and right_ans is the other N elements ...
161
You are given an integer array `nums` of `2 * n` integers. You need to partition `nums` into **two** arrays of length `n` to **minimize the absolute difference** of the **sums** of the arrays. To partition `nums`, put each element of `nums` into **one** of the two arrays. Return _the **minimum** possible absolute diff...
Let's use floodfill to iterate over the islands of the second grid Let's note that if all the cells in an island in the second grid if they are represented by land in the first grid then they are connected hence making that island a sub-island
Very fast python3 solution | 698 ms - faster than 100% solutions | meet-in-middle + 2 pointers
partition-array-into-two-arrays-to-minimize-sum-difference
0
1
# Complexity\n- Time complexity: $$O(2^n \\cdot n^{1.5})$$\n<!-- Add your time complexity here, e.g. $$O(2^n)$$ -->\n\n- Space complexity: $$O(2^n)$$\n<!-- Add your space complexity here, e.g. $$O(2^n)$$ -->\n\n\nTime complexity of `get_subsets_sums` is $$O(2^n)$$,\ntime complexity of `calc` is $$O(n \\cdot k \\cdot lo...
1
You are given an integer array `nums` of `2 * n` integers. You need to partition `nums` into **two** arrays of length `n` to **minimize the absolute difference** of the **sums** of the arrays. To partition `nums`, put each element of `nums` into **one** of the two arrays. Return _the **minimum** possible absolute diff...
Let's use floodfill to iterate over the islands of the second grid Let's note that if all the cells in an island in the second grid if they are represented by land in the first grid then they are connected hence making that island a sub-island
Intuitive Greedy solution with Python3
minimum-number-of-moves-to-seat-everyone
0
1
# Intuition\nHere we have:\n- `seats` and `students` lists\n- our goal is to move `students` to `seats` **optimally**\n\nThere\'re some `students`, who we don\'t need to move, as they\'re sitting in the right place.\n\nTo make an **optimal decision** we should map `seats` to `students` and minimize a distance between `...
1
There are `n` seats and `n` students in a room. You are given an array `seats` of length `n`, where `seats[i]` is the position of the `ith` seat. You are also given the array `students` of length `n`, where `students[j]` is the position of the `jth` student. You may perform the following move any number of times: * ...
Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt
PYHTON SOLUTION FOR BEGGINERS || VERY EASY USING
minimum-number-of-moves-to-seat-everyone
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
There are `n` seats and `n` students in a room. You are given an array `seats` of length `n`, where `seats[i]` is the position of the `ith` seat. You are also given the array `students` of length `n`, where `students[j]` is the position of the `jth` student. You may perform the following move any number of times: * ...
Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt
Python ✅✅✅ || Faster than 86.11%, Memory Beats 97.69%
minimum-number-of-moves-to-seat-everyone
0
1
# Code\n```\nclass Solution:\n def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:\n moves = 0\n seats.sort()\n students.sort()\n for s in range(len(students)):\n moves += abs(students[s]-seats[s])\n return moves\n```\n\n![image.png](https://assets.le...
2
There are `n` seats and `n` students in a room. You are given an array `seats` of length `n`, where `seats[i]` is the position of the `ith` seat. You are also given the array `students` of length `n`, where `students[j]` is the position of the `jth` student. You may perform the following move any number of times: * ...
Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt
[Java/Python 3] Sort both and sum the corresponding difference.
minimum-number-of-moves-to-seat-everyone
1
1
```java\n public int minMovesToSeat(int[] seats, int[] students) {\n Arrays.sort(seats);\n Arrays.sort(students);\n int moves = 0;\n for (int i = 0; i < seats.length; ++i) {\n moves += Math.abs(seats[i] - students[i]);\n }\n return moves;\n }\n```\n```python\n ...
26
There are `n` seats and `n` students in a room. You are given an array `seats` of length `n`, where `seats[i]` is the position of the `ith` seat. You are also given the array `students` of length `n`, where `students[j]` is the position of the `jth` student. You may perform the following move any number of times: * ...
Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt
✅✔🔥 EASY PYTHON3 SOLUTION 🔥✅✔ ONE-LINE
minimum-number-of-moves-to-seat-everyone
0
1
if it is helpful please **Upvote** me\n ``` \n def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:\n seats.sort()\n students.sort()\n count = 0\n for i in range(len(seats)):\n count += abs(seats[i]-students[i])\n return count\n``` \n**One line approac...
1
There are `n` seats and `n` students in a room. You are given an array `seats` of length `n`, where `seats[i]` is the position of the `ith` seat. You are also given the array `students` of length `n`, where `students[j]` is the position of the `jth` student. You may perform the following move any number of times: * ...
Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt
Math Bazooka | 1 liner | Earthmover Distance Solution
minimum-number-of-moves-to-seat-everyone
0
1
Today we will be nuking mosquitos by using the [Earthmover distance](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.wasserstein_distance.html). \n\nExcluding an import, this yields a 1-liner.\n\nIs that overkill? Yes, absolutely.\n\n```\nfrom scipy.stats import wasserstein_distance as EMD\nclass Solut...
3
There are `n` seats and `n` students in a room. You are given an array `seats` of length `n`, where `seats[i]` is the position of the `ith` seat. You are also given the array `students` of length `n`, where `students[j]` is the position of the `jth` student. You may perform the following move any number of times: * ...
Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt