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
Efficient Union Find using only water cells | Beats 100%
last-day-where-you-can-still-cross
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTop and bottom rows are connected via land if and only if the first and last columns are not connected via water. For this to hold water is considered to be connected in 8 directions because you can pass between land only in 4 directions....
3
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively. Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. ...
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
Python3 Solution
last-day-where-you-can-still-cross
0
1
\n```\nclass Solution:\n def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:\n n = row * col\n root, left, right = list(range(n)), [0] * n, [0] * n \n for i in range(col):\n for j in range(row):\n left[i * row + j] = i\n right[i...
2
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively. Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. ...
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
python binary search with bfs
last-day-where-you-can-still-cross
0
1
```\nclass Solution:\n def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:\n \n cells = list(map(tuple, cells))\n \n def search(day):\n queue = deque([(1,i) for i in range(1, col+1)])\n visited = set(cells[:day])\n while queue:\n...
2
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively. Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. ...
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
✅BS + BFS || C++ || JAVA || PYTHON || Beginner Friendly🔥🔥🔥
last-day-where-you-can-still-cross
1
1
# Intuition:\n\nThe intuition behind the problem is to find the latest day where it is still possible to cross the grid by incrementally adding cells and checking if a path exists from the top row to the bottom row, utilizing binary search to optimize the search process.\n\n# Explanation:\n**Binary Search:**\n1. Initia...
116
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively. Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. ...
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
Python: Union-Find to detect whether the largest longitudinal span covers all the columns
last-day-where-you-can-still-cross
0
1
# Code\n```\nclass Solution:\n def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:\n parent, rank = [], [] # typical union-find\n span = [] # for every node in union-find DS, the longitudinal span it covers\n\n matrix = [[None] * col for _ in range(row)]\n # Non...
1
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively. Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. ...
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
Python solution with explaination (DP solution)
last-day-where-you-can-still-cross
0
1
# Intuition\nApproach 1 (Two greedy approach):\n1.1 Being greedy in the first approach we can create a matrix r*c filled with 0 at the start. In each step we will fill water in the matrix and will itterate throughout column starting with row = 0. If we are able to reach the last row that means the path is not closed ye...
1
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively. Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. ...
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
Design solution with modified DJS | detailed explanation
last-day-where-you-can-still-cross
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nInstead of checking if there is a connection between top and bottom, we can go from the end and merge the islands that appear.\nWe can merge islands using DJS.\nTo quickly check if there is an island connecting the top and bottom, we can ...
1
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively. Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. ...
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
Python short and clean. DSU (Disjoint-Set-Union). Functional programming.
last-day-where-you-can-still-cross
0
1
# Approach\nTL;DR, Similar to [Editorial solution Approach 3](https://leetcode.com/problems/last-day-where-you-can-still-cross/editorial/) but cleaner and functional.\n\n# Complexity\n- Time complexity: $$O(m \\cdot n)$$\n\n- Space complexity: $$O(m \\cdot n)$$\n\nwhere\n`m is number of rows`,\n`n is number of columns`...
2
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively. Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. ...
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
Beginner Level Python Code || Easy to Understand || With Expln🐍🐍
last-day-where-you-can-still-cross
0
1
# Approach\nBinary searching the last reachable day\n- if reachable, then the last day should be after current day\n- if not reachable, then the last day should be before the current day\n\nTo check if the day is reachable - \n- make a grid of the land configuration of the particular day\n- travel in bfs/dfs from all t...
1
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively. Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. ...
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
Easy solution for understanding
find-if-path-exists-in-graph
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connecte...
What is the upper bound for the number of seconds? Simulate the process of allocating memory.
Union find(beats 97%) and simple DFS solution using Python3
find-if-path-exists-in-graph
0
1
![image.png](https://assets.leetcode.com/users/images/172ac647-9625-4a0d-a3e0-447dbff6635f_1698931695.4002445.png)\n\n\n# Union find\n```\nclass Solution:\n def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:\n # Helper function to find the representative of a node\n ...
2
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connecte...
What is the upper bound for the number of seconds? Simulate the process of allocating memory.
Beats 95% | BFS | CodeDominar Solution
find-if-path-exists-in-graph
0
1
# Code\n```\nclass Solution:\n def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:\n adj_list = {i:[] for i in range(n)}\n for v1,v2 in edges:\n adj_list[v1].append(v2)\n adj_list[v2].append(v1)\n q = deque()\n q.append(source)...
1
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connecte...
What is the upper bound for the number of seconds? Simulate the process of allocating memory.
fast Solution in Python/Java/C++
find-if-path-exists-in-graph
0
1
# Intuition\nSimple and fast Solution in Python/Java/C++\n# Complexity\n- Time complexity:\n \n time complexity of O(n + m) \n\n- Space complexity:\n \n space complexity of O(n) \n\n```python []\nclass Solution:\n def validPath(self, n: int, edges: List[List[int]], source: int, destinatio...
2
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connecte...
What is the upper bound for the number of seconds? Simulate the process of allocating memory.
By iterating
find-if-path-exists-in-graph
0
1
\n# Code\n```\nclass Solution:\n def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:\n graphs_path = defaultdict(set)\n for i,j in edges:\n graphs_path[i].add(j)\n graphs_path[j].add(i)\n paths_visited = {source}\n paths_to_vis...
1
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connecte...
What is the upper bound for the number of seconds? Simulate the process of allocating memory.
Easy | Python | Recursive Solution | DFS | Graph
find-if-path-exists-in-graph
0
1
# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def validPath(self, n: int, arr: List[List[int]], source: int, destination: int) -> bool:\n\n visited = set()\n graph = defaultdict(list)\n\n for i in arr:\n graph[i[0]].append(i[1])\n graph[i[1]].append(i[...
1
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connecte...
What is the upper bound for the number of seconds? Simulate the process of allocating memory.
[Python3] greedy
minimum-time-to-type-word-using-special-typewriter
0
1
\n```\nclass Solution:\n def minTimeToType(self, word: str) -> int:\n ans = len(word)\n prev = "a"\n for ch in word: \n val = (ord(ch) - ord(prev)) % 26 \n ans += min(val, 26 - val)\n prev = ch\n return ans \n```
61
There is a special typewriter with lowercase English letters `'a'` to `'z'` arranged in a **circle** with a **pointer**. A character can **only** be typed if the pointer is pointing to that character. The pointer is **initially** pointing to the character `'a'`. Each second, you may perform one of the following operat...
null
[Java/Python 3] Compute the shorter distance, w/ brief explanation and analysis.
minimum-time-to-type-word-using-special-typewriter
1
1
1. Initialize the `prev` as `a`;\n2. Traverse the `word`, for each character, compute the distances from current character, `cur`, to previous one, `prev`, clockwise and counter-clockwise, respectively; Choose the minimum between them; \n3. Count in `1` second for each typing character; therefore we can initialize `cnt...
47
There is a special typewriter with lowercase English letters `'a'` to `'z'` arranged in a **circle** with a **pointer**. A character can **only** be typed if the pointer is pointing to that character. The pointer is **initially** pointing to the character `'a'`. Each second, you may perform one of the following operat...
null
[Python3] greedy
maximum-matrix-sum
0
1
\n```\nclass Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n ans = mult = 0\n val = inf \n for i in range(len(matrix)): \n for j in range(len(matrix)):\n ans += abs(matrix[i][j])\n val = min(val, abs(matrix[i][j]))\n i...
15
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summatio...
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
Python 5LoC, easy to understand
maximum-matrix-sum
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nif there are even numbers of neg, then we can just filp them all.\n\nif there are odd numbers of neg, then we can just filp them remaining only one.\n\n**comes the point:**\n\nIf it\'s the abs smallest val, leave it be.\n\nElse, we can ...
1
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summatio...
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
Python easy to read and understand | greedy
maximum-matrix-sum
0
1
```\nclass Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n n = len(matrix)\n cnt, res = 0, 0\n mn = float("inf")\n \n for i in range(n):\n for j in range(n):\n res += abs(matrix[i][j])\n if matrix[i][j] < 0:\n ...
0
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summatio...
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
Check for even/odd # of negatives using XOR operation
maximum-matrix-sum
0
1
An even number of negatives can always be rearranged to eliminate all negatives, so the solution is the sum of the absolute values of the matrix elements.\nIf you don\'t understand this, think of just a single row:\ne.g.` -1 1 -1 1`\nYou can always shift the two negatives adjacent to each other and make them positive, ...
0
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summatio...
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
Sum - Min - Sink - O(n^2)
maximum-matrix-sum
0
1
# Complexity\n```\n- Time complexity: O(n^2)\n- Space complexity: O(1)\n```\n# Code\n```python\nclass Solution:\n def maxMatrixSum(self, M: List[List[int]]) -> int:\n return sum(sum(abs(c) for c in r) for r in M) \\\n + -min((min((abs(c) for c in r), default=maxsize) for r in M), default=maxsize) \...
0
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summatio...
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
Simple solution
maximum-matrix-sum
0
1
```\nclass Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n cnt_neg, min_abs_num, sum_abs_num = 0, abs(matrix[0][0]), 0\n for row in matrix:\n for num in row:\n cnt_neg += (num < 0)\n min_abs_num = min(abs(num), min_abs_num)\n ...
0
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summatio...
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
maximum-matrix-sum
maximum-matrix-sum
0
1
# Code\n```\nclass Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n l = []\n for i in matrix:\n l+=i\n a = float("inf")\n count = 0\n val = 0\n for i in l:\n if i<0:\n count+=1\n a = min(a,abs(i))\n ...
0
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summatio...
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
Negate pairs of negatives
maximum-matrix-sum
0
1
# Intuition\nIf there are adjacent negatives, we could get rid both of them.\n\nIf one of adjacent numbers are negative, the negative could disseminate the minus sign to one of it\'s neighbor. \nHence the minus signs are gathered and annihilated until at most one minus sign remains.\n\n# Complexity\n- Time complexity: ...
0
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summatio...
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
Easy Python Solution - One Pass
maximum-matrix-sum
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince we can perform any number of operations, then we will always be able to continue "moving" the negative values around until they collide with another negative value. \n\nWe will always be able to pair all negative values if the total...
0
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summatio...
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
python super easy greedy
maximum-matrix-sum
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summatio...
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
Python - Dijkstra's Algorithm (Min Heap Implementation) >90% time score
number-of-ways-to-arrive-at-destination
0
1
```\nfrom heapq import *\nclass Solution:\n def countPaths(self, n: int, roads: List[List[int]]) -> int:\n # create adjacency list\n adj_list = defaultdict(list)\n for i,j,k in roads:\n adj_list[i].append((j,k))\n adj_list[j].append((i,k))\n \n start = 0\n...
10
You are in a city that consists of `n` intersections numbered from `0` to `n - 1` with **bi-directional** roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an in...
One solution is to try all possible splits using backtrack Look out for trailing zeros in string
[Python3] dp
number-of-ways-to-separate-numbers
0
1
\n```\nclass Solution:\n def numberOfCombinations(self, num: str) -> int:\n n = len(num)\n lcs = [[0]*(n+1) for _ in range(n)]\n for i in reversed(range(n)): \n for j in reversed(range(i+1, n)): \n if num[i] == num[j]: lcs[i][j] = 1 + lcs[i+1][j+1]\n \n de...
5
You wrote down many **positive** integers in a string called `num`. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was **non-decreasing** and that **no** integer had leading zeros. Return _the **number of possible lists of integers** that y...
Is there a way to order the intervals and queries such that it takes less time to query? Is there a way to add and remove intervals by going from the smallest query to the largest query to find the minimum size?
[Python3] Partition for Repeated Single Digit, beats 92% time
number-of-ways-to-separate-numbers
0
1
# Intuition\nI started to write the intuitive algorithm and came up with a faster way to solve the last test case.\n\n# Approach\n## For more than one digit in the input:\n\nThe method `comb` has the parameters `i`, `val`, and `digits`. It returns the amount of different combinations of splits that are:\n1. splitting t...
0
You wrote down many **positive** integers in a string called `num`. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was **non-decreasing** and that **no** integer had leading zeros. Return _the **number of possible lists of integers** that y...
Is there a way to order the intervals and queries such that it takes less time to query? Is there a way to add and remove intervals by going from the smallest query to the largest query to find the minimum size?
Python Solution with TC : O(n^2) and SC : O(n)
number-of-ways-to-separate-numbers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTry to come up first with recursive equation\n# Approach\n<!-- Describe your approach to solving the problem. -->\nRecursive Equation turned into bottom up DP\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O...
0
You wrote down many **positive** integers in a string called `num`. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was **non-decreasing** and that **no** integer had leading zeros. Return _the **number of possible lists of integers** that y...
Is there a way to order the intervals and queries such that it takes less time to query? Is there a way to add and remove intervals by going from the smallest query to the largest query to find the minimum size?
Python | DP + accumulate sum
number-of-ways-to-separate-numbers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCreate a DP table dp with $N\\times N$ dimension.\nDP rule:\n$dp[s][i] = f(s, i) + \\sum_{j = i + i - s + 1}^{n-1}dp[i][j]$\n\nwhere $f(s,i) = 1$ if $num[s:i] <= num[i: i +i -s]$; else $f(s,i) = 0$\n\nInorder to calculate $\\sum_{j = i + ...
0
You wrote down many **positive** integers in a string called `num`. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was **non-decreasing** and that **no** integer had leading zeros. Return _the **number of possible lists of integers** that y...
Is there a way to order the intervals and queries such that it takes less time to query? Is there a way to add and remove intervals by going from the smallest query to the largest query to find the minimum size?
Solution
number-of-ways-to-separate-numbers
1
1
```C++ []\nclass Solution\n{\npublic:\n int numberOfCombinations(string num)\n {\n if(num == "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111...
0
You wrote down many **positive** integers in a string called `num`. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was **non-decreasing** and that **no** integer had leading zeros. Return _the **number of possible lists of integers** that y...
Is there a way to order the intervals and queries such that it takes less time to query? Is there a way to add and remove intervals by going from the smallest query to the largest query to find the minimum size?
💡Intuitive| ⏳0ms 🥇Beats 100% | ✅ Beginner's Friendly Explanation
find-unique-binary-string
0
1
![Screenshot (206).png](https://assets.leetcode.com/users/images/342810d1-b3d0-4857-8d04-231c9fba4d34_1700108716.9560091.png)\n\n# Intuition\nCantor\'s diagonal argument is a mathematical proof technique used to show that the set of real numbers is uncountably infinite. It\'s often applied in discussions related to the...
10
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanatio...
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
✅ 100% efficient | Pruning + Memoization | Dynamic Programming | Explanation
minimize-the-difference-between-target-and-chosen-elements
0
1
**Explanation:**\n\n\nPlease note following important observations from question,\n1. We must choose exactly one element from each row\n2. Minimize the diff between target and the sum of all chosen elements\n\nApproach (and how to solve TLE)\n\nNow, the general idea is to explore all possibilities, however, that\'ll be...
25
You are given an `m x n` integer matrix `mat` and an integer `target`. Choose one integer from **each row** in the matrix such that the **absolute difference** between `target` and the **sum** of the chosen elements is **minimized**. Return _the **minimum absolute difference**_. The **absolute difference** between t...
null
Python 3 || 4 lines, sets || T/M: 87% / 47%
minimize-the-difference-between-target-and-chosen-elements
0
1
```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n\n mat = [set(row) for row in mat]\n \n rSet = set(mat.pop())\n\n for row in mat: rSet = {m+n for m in row for n in rSet}\n \n return min(abs(n - target) for n in rSet)\n\n```\...
5
You are given an `m x n` integer matrix `mat` and an integer `target`. Choose one integer from **each row** in the matrix such that the **absolute difference** between `target` and the **sum** of the chosen elements is **minimized**. Return _the **minimum absolute difference**_. The **absolute difference** between t...
null
85% TC and 84% SC easy python solution
minimize-the-difference-between-target-and-chosen-elements
0
1
```\ndef minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n\tm = len(mat)\n\tfor i in range(m):\n\t\tmat[i].sort()\n\tq = set([0])\n\tfor i in range(m):\n\t\ttemp = set()\n\t\tfor num1 in q:\n\t\t\tfor num2 in mat[i]:\n\t\t\t\ttemp.add(num1+num2)\n\t\t\t\tif(num1+num2 > target):\n\t\t\t\t\tbreak\n...
1
You are given an `m x n` integer matrix `mat` and an integer `target`. Choose one integer from **each row** in the matrix such that the **absolute difference** between `target` and the **sum** of the chosen elements is **minimized**. Return _the **minimum absolute difference**_. The **absolute difference** between t...
null
C and Python solutions. C beats 100% in Space and Time.
minimize-the-difference-between-target-and-chosen-elements
0
1
# Intuition\nStore all the possible sums in a set!\nSets are perfect for checking existence/membership.\n\n# Approach\nAgain, we only need to store all the sums. Better yet, we can break it into sub-problems, and instead use a set, say, `prev`, to store the sums **of a given row**. Then, sum the values stored in the `p...
0
You are given an `m x n` integer matrix `mat` and an integer `target`. Choose one integer from **each row** in the matrix such that the **absolute difference** between `target` and the **sum** of the chosen elements is **minimized**. Return _the **minimum absolute difference**_. The **absolute difference** between t...
null
Easy Explanation for Noobs + Python code with comments
find-array-given-subset-sums
0
1
**Some key principles of a set that we will use to construct our solution**\n1. If the size of a set is `n` then its superset has a size of `2^n`. Hence, any superset is always divisible in two equal parts.\n2. Any superset must have an empty set. The sum of elements of any empty set is `0`, hence any set containing al...
81
You are given an integer `n` representing the length of an unknown array that you are trying to recover. You are also given an array `sums` containing the values of all `2n` **subset sums** of the unknown array (in no particular order). Return _the array_ `ans` _of length_ `n` _representing the unknown array. If **mul...
Is there a way we can know beforehand which nodes to delete? Count the number of appearances for each number.
Divide and Conquer in Python 3, Example Explained
find-array-given-subset-sums
0
1
Basically I did the following:\n1. Sort the summaries.\n2. Divide it by two groups so that every single value in the higher group has a conterpart in lower group. And the differences (set it to positive for now) are the same among all such pairs.\n3. If zero is in lower group, return the lower group and the difference,...
6
You are given an integer `n` representing the length of an unknown array that you are trying to recover. You are also given an array `sums` containing the values of all `2n` **subset sums** of the unknown array (in no particular order). Return _the array_ `ans` _of length_ `n` _representing the unknown array. If **mul...
Is there a way we can know beforehand which nodes to delete? Count the number of appearances for each number.
Divide and conquer (beats 100% at the time of writing)
find-array-given-subset-sums
0
1
# Intuition\n\nWhat matters is the subset sum values and their multiplicities.\nThe largest possible subset sum value for example is the sum of all non-negative elements in the array and its multiplicity is the $2^k$ where $k$ is the numver of zeros in the array. Then $2^k$ is a factor in all multiplicities and after d...
0
You are given an integer `n` representing the length of an unknown array that you are trying to recover. You are also given an array `sums` containing the values of all `2n` **subset sums** of the unknown array (in no particular order). Return _the array_ `ans` _of length_ `n` _representing the unknown array. If **mul...
Is there a way we can know beforehand which nodes to delete? Count the number of appearances for each number.
90% Runtime, 85% Memory with Simple Code
minimum-difference-between-highest-and-lowest-of-k-scores
0
1
\n\n# Approach\n`res = nums[k-1] - nums[0]`\nSince nums is sorted, `nums[k-1] - nums[0]` returns max dif.\n\n`res = min(res, nums[i] - nums[i - k + 1])`\nFrom window of size k, the far left is the minimum \nand far right is the maximum value in the window since nums is sorted. \n`nums[i]` : Far right\n`nums[i - k + 1])...
1
You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`. Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**. Return _the **m...
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at l...
Python simple solution
minimum-difference-between-highest-and-lowest-of-k-scores
0
1
**Python :**\n\n```\ndef minimumDifference(self, nums: List[int], k: int) -> int:\n\tif len(nums) <= 1:\n\t\treturn 0\n\n\tnums = sorted(nums)\n\tres = nums[k-1] - nums[0]\n\n\tfor i in range(k, len(nums)):\n\t\tres = min(res, nums[i] - nums[i - k + 1])\n\n\treturn res\n```\n\n**Like it ? please upvote !**
32
You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`. Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**. Return _the **m...
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at l...
Python 2 line + CPP Soln With Explanation
minimum-difference-between-highest-and-lowest-of-k-scores
0
1
```\nThis Q is asking what is the minimum difference between nums[i] and nums[i+(k-1)] for all.\n k-1 beacuse Total K Values = from nums[i] to nums[i+k-1]\n ------- -----------\n 1 value k-1 values\n ...
2
You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`. Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**. Return _the **m...
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at l...
Python3 Beats 99% sliding window of length K
minimum-difference-between-highest-and-lowest-of-k-scores
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
You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`. Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**. Return _the **m...
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at l...
Python || 99.43% Faster || Sliding Window + Sorting
minimum-difference-between-highest-and-lowest-of-k-scores
0
1
```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n m,n=100001,len(nums)\n i,j=0,k-1\n while j<n:\n m=min(m,nums[j]-nums[i])\n i+=1\n j+=1\n return m\n```\n\n**An upvote will be encouraging**
6
You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`. Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**. Return _the **m...
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at l...
Python 99.70% time solution (beginner friendly)
minimum-difference-between-highest-and-lowest-of-k-scores
0
1
![Screenshot 2022-12-26 at 10.06.37 PM.png](https://assets.leetcode.com/users/images/d2266660-7868-44d6-9070-0820cc451cbe_1672121376.6683125.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSort the input array first so it is easier to work with, then implement sliding window ap...
1
You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`. Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**. Return _the **m...
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at l...
Python Solution
minimum-difference-between-highest-and-lowest-of-k-scores
0
1
# Intuition\nThe hardest issue was trying to figure out how to calculate the difference, based on the number of k students, no matter the size of the list. And then check each difference and compare it to the minimum difference, and then return the lowest possible difference. \n\n# Approach\nSimple usage of python buil...
2
You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`. Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**. Return _the **m...
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at l...
Simple and short Python solution O(n)
minimum-difference-between-highest-and-lowest-of-k-scores
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 **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`. Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**. Return _the **m...
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at l...
nlogn
minimum-difference-between-highest-and-lowest-of-k-scores
0
1
\n\n# Code\n```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort() # we sort the element\n l,r = 0,k-1\n res = float("inf")\n\n while r < len(nums):\n res = min(res,nums[r]-nums[l])\n l,r = l+1,r+1\n return res\n\n# t...
1
You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`. Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**. Return _the **m...
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at l...
Python-3- sliding window
minimum-difference-between-highest-and-lowest-of-k-scores
0
1
Slide the window and update the min. each time we increase the window, if needed!\n\n```\ndef minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n l, r = 0, k-1\n \n minDiff = float(\'inf\')\n \n while r < len(nums):\n minDiff = min(minDiff, nums[...
10
You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`. Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**. Return _the **m...
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at l...
Best Easy approach || 96.84% Beat || Python
minimum-difference-between-highest-and-lowest-of-k-scores
0
1
# Intuition\nSorting\n\n# Approach\nSliding Window\n\n# Complexity\n- Time complexity:\nO(NlogN)\n\n- Space complexity:\nO(K)\n\n# Code\n```\nimport math\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n lst=[]\n res=math.inf\n nums.sort()\n for i in range(...
1
You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`. Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**. Return _the **m...
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at l...
Minimum Difference Between Highest and Lowest of K Scores
minimum-difference-between-highest-and-lowest-of-k-scores
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nusing list append method and two pointer algorithm\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ntwo pointer algorithm\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nn...
1
You are given a **0-indexed** integer array `nums`, where `nums[i]` represents the score of the `ith` student. You are also given an integer `k`. Pick the scores of any `k` students from the array so that the **difference** between the **highest** and the **lowest** of the `k` scores is **minimized**. Return _the **m...
Since both arrays are sorted in a non-increasing way this means that for each value in the first array. We can find the farthest value smaller than it using binary search. There is another solution using a two pointers approach since the first array is non-increasing the farthest j such that nums2[j] ≥ nums1[i] is at l...
beats 99.5%
find-the-kth-largest-integer-in-the-array
0
1
\n\n# Code\n```\nclass Solution:\n def kthLargestNumber(self, nums: List[str], k: int) -> str:\n # time complexity -- O(klogn)\n\n maxHeap = [-int(n) for n in nums]\n heapq.heapify(maxHeap)\n\n while k > 1:\n heapq.heappop(maxHeap)\n k-=1\n return str(-maxHeap...
1
You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros. Return _the string that represents the_ `kth` _**largest integer** in_ `nums`. **Note**: Duplicate numbers should be counted distinctly. For example, if `nums` is `[ "1 ", "2 ", "2 "]`, `"2 ...
Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array?
2 line code in python
find-the-kth-largest-integer-in-the-array
0
1
\nclass Solution:\n def kthLargestNumber(self, nums: List[str], k: int) -> str:\n l=list(map(int,nums))\n l.sort()\n return str(l[-k])\n```
1
You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros. Return _the string that represents the_ `kth` _**largest integer** in_ `nums`. **Note**: Duplicate numbers should be counted distinctly. For example, if `nums` is `[ "1 ", "2 ", "2 "]`, `"2 ...
Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array?
Best python 3 solution , beats 92% ms
find-the-kth-largest-integer-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:\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
You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros. Return _the string that represents the_ `kth` _**largest integer** in_ `nums`. **Note**: Duplicate numbers should be counted distinctly. For example, if `nums` is `[ "1 ", "2 ", "2 "]`, `"2 ...
Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array?
Python || 1 Liner || 94.90% Faster || Sorting
find-the-kth-largest-integer-in-the-array
0
1
```\nclass Solution:\n def kthLargestNumber(self, nums: List[str], k: int) -> str:\n return sorted(nums, key= lambda i : int(i))[-k]\n```\n\n**An upvote will be encouaging**
4
You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros. Return _the string that represents the_ `kth` _**largest integer** in_ `nums`. **Note**: Duplicate numbers should be counted distinctly. For example, if `nums` is `[ "1 ", "2 ", "2 "]`, `"2 ...
Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array?
Python | The Right Way during Interview | Comparators
find-the-kth-largest-integer-in-the-array
0
1
Although, this ways works, ie by directly converting all string to integer. Then sort and reverse.\n\n```\nclass Solution:\n def kthLargestNumber(self, nums: List[str], k: int) -> str:\n nums = sorted(map(int, nums), reverse=True)\n return str(nums[k-1])\n```\n\nThis works because there is no limit to ...
40
You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros. Return _the string that represents the_ `kth` _**largest integer** in_ `nums`. **Note**: Duplicate numbers should be counted distinctly. For example, if `nums` is `[ "1 ", "2 ", "2 "]`, `"2 ...
Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array?
Best python 3 solution , beats 92% ms
find-the-kth-largest-integer-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:\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 an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros. Return _the string that represents the_ `kth` _**largest integer** in_ `nums`. **Note**: Duplicate numbers should be counted distinctly. For example, if `nums` is `[ "1 ", "2 ", "2 "]`, `"2 ...
Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array?
Classic quick select algorithm in Python
find-the-kth-largest-integer-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: O(n), with the worst case O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your s...
1
You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros. Return _the string that represents the_ `kth` _**largest integer** in_ `nums`. **Note**: Duplicate numbers should be counted distinctly. For example, if `nums` is `[ "1 ", "2 ", "2 "]`, `"2 ...
Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array?
2 GENEROUS lines of code, 70% TC and 57% SC
find-the-kth-largest-integer-in-the-array
0
1
```\ndef kthLargestNumber(self, nums: List[str], k: int) -> str:\n\tnums.sort(key = lambda x:int(x), reverse = True)\n\treturn nums[k-1]\n```
1
You are given an array of strings `nums` and an integer `k`. Each string in `nums` represents an integer without leading zeros. Return _the string that represents the_ `kth` _**largest integer** in_ `nums`. **Note**: Duplicate numbers should be counted distinctly. For example, if `nums` is `[ "1 ", "2 ", "2 "]`, `"2 ...
Is there a way we can sort the elements to simplify the problem? Can we find the maximum min-product for every value in the array?
1987. Number of Unique Good Subsequences [Python]
number-of-unique-good-subsequences
0
1
\n\n```python\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n mod = 10**9 + 7\n dp = [[0, 0] for _ in range(2)] # dp[i][j] represents count of subsequences ending at index i with last element j (0 or 1)\n n = len(binary)\n \n for ch in binary:\n ...
2
You are given a binary string `binary`. A **subsequence** of `binary` is considered **good** if it is **not empty** and has **no leading zeros** (with the exception of `"0 "`). Find the number of **unique good subsequences** of `binary`. * For example, if `binary = "001 "`, then all the **good** subsequences are `[...
Try using a set to find out the number of distinct characters in a substring.
Python (Simple Maths)
number-of-unique-good-subsequences
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
You are given a binary string `binary`. A **subsequence** of `binary` is considered **good** if it is **not empty** and has **no leading zeros** (with the exception of `"0 "`). Find the number of **unique good subsequences** of `binary`. * For example, if `binary = "001 "`, then all the **good** subsequences are `[...
Try using a set to find out the number of distinct characters in a substring.
Python, runtime O(n), memory O(1)
number-of-unique-good-subsequences
0
1
Got idea here: https://leetcode.com/problems/number-of-unique-good-subsequences/solutions/1431802/c-clean-dp-solution-with-explanation-time-o-n-space-o-1/\n```\nclass Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n end0 = end1 = hasZero = 0\n mod = 10**9+7\n for e in ...
0
You are given a binary string `binary`. A **subsequence** of `binary` is considered **good** if it is **not empty** and has **no leading zeros** (with the exception of `"0 "`). Find the number of **unique good subsequences** of `binary`. * For example, if `binary = "001 "`, then all the **good** subsequences are `[...
Try using a set to find out the number of distinct characters in a substring.
The Easier Way | DP O(n) | Backward Iteration
number-of-unique-good-subsequences
0
1
# Intuition\nSuppose ```dp[i][bit]``` shows number of subsequences with all of it\'s bit indices greater or equal to ```i``` and starts with bit ```bit```(0, 1). So, the recursive relation would be:\n```dp[i][bit] = dp[i + 1][0] + dp[i + 1][1] + 1```(+1 for single 1 or single zero). Therefore the optimized space solut...
0
You are given a binary string `binary`. A **subsequence** of `binary` is considered **good** if it is **not empty** and has **no leading zeros** (with the exception of `"0 "`). Find the number of **unique good subsequences** of `binary`. * For example, if `binary = "001 "`, then all the **good** subsequences are `[...
Try using a set to find out the number of distinct characters in a substring.
O(n log n) using divide and conquer
find-the-middle-index-in-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSo we notice that for index `i` and index `i + 1`, most of the sum on the left and right side are shared. In particular, the left side of index `i` is `sum(nums[0..i-1])` and the left side of `i + 1` is `sum(nums[0..i-1]) + nums[i]`, so t...
7
Given a **0-indexed** integer array `nums`, find the **leftmost** `middleIndex` (i.e., the smallest amongst all the possible ones). A `middleIndex` is an index where `nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]`. If `middleIndex == 0`, the lef...
null
Python simple O(n) solution
find-the-middle-index-in-array
0
1
**Python :**\n\n```\ndef findMiddleIndex(self, nums: List[int]) -> int: \n\tleftSum = 0\n\trightSum = sum(nums)\n\n\tfor i in range(len(nums)):\n\t\tif leftSum == rightSum - nums[i]:\n\t\t\treturn i\n\n\t\tleftSum += nums[i]\n\t\trightSum -= nums[i]\n\n\treturn -1\n```\n\n**Like it ? please upvote !**
60
Given a **0-indexed** integer array `nums`, find the **leftmost** `middleIndex` (i.e., the smallest amongst all the possible ones). A `middleIndex` is an index where `nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]`. If `middleIndex == 0`, the lef...
null
Python | Easy Solution✅
find-the-middle-index-in-array
0
1
# Code\u2705\n```\nclass Solution:\n def findMiddleIndex(self, nums: List[int]) -> int:\n left = 0\n right = sum(nums)\n for index, num in enumerate(nums):\n right -= num\n if left == right:\n return index\n left += num\n \n retur...
4
Given a **0-indexed** integer array `nums`, find the **leftmost** `middleIndex` (i.e., the smallest amongst all the possible ones). A `middleIndex` is an index where `nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]`. If `middleIndex == 0`, the lef...
null
[python3] Simple and easy Beats 97% runtime
find-the-middle-index-in-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)$$ --...
2
Given a **0-indexed** integer array `nums`, find the **leftmost** `middleIndex` (i.e., the smallest amongst all the possible ones). A `middleIndex` is an index where `nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]`. If `middleIndex == 0`, the lef...
null
[Python] - Commented Rolling Window
find-the-middle-index-in-array
0
1
The exercise could be solved with prefix sum, but also with a rolling window.\n\nWe can compute the whole sum in one pass. This is our initial sum to the right, our sum to the left is zero. Then for every index, we first subtract current index from right sum, compare the sums and after that add the index to the left su...
1
Given a **0-indexed** integer array `nums`, find the **leftmost** `middleIndex` (i.e., the smallest amongst all the possible ones). A `middleIndex` is an index where `nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]`. If `middleIndex == 0`, the lef...
null
python3 solution using queue only,(bfs) used simple to implement with detailed solution
find-all-groups-of-farmland
0
1
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe can have dimensions stored in m,n of the land\nif we find an index storing 1 we will start with it by adding it to an array b which will store the topleft and bottomright indices\nwe have a queue with index `(i,j)` in it and we pop the first el...
1
You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. N...
The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order.
[Python3] DFS (easy to understand)
find-all-groups-of-farmland
0
1
### Idea\n- first we need to iterative through all the positions in the square from the left to the right, top to the bottom.\n- If the land[i][j] == 1, the current coordinate (i, j) will be the top left position and then we will dfs from that coordinate to find to bottom right coordinate.\n- The dfs function will stop...
18
You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. N...
The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order.
✅[Python] Simple and Clean, beats 99.09%✅
find-all-groups-of-farmland
0
1
### Please upvote if you find this helpful. \u270C\n<img src="https://assets.leetcode.com/users/images/b8e25620-d320-420a-ae09-94c7453bd033_1678818986.7001078.jpeg" alt="Cute Robot - Stable diffusion" width="200"/>\n\n*This is an NFT*\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->...
2
You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. N...
The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order.
python3 easy to understand
find-all-groups-of-farmland
0
1
```\ndef findFarmland(self, grid):\n self.ans=[]\n row=len(grid)\n col=len(grid[0])\n \n def helper(i,j,grid):\n if i<0 or j<0 or j>=len(grid[0]) or i>=len(grid) or grid[i][j]==0:return (0,0)\n (nx,ny)=(i,j)\n grid[i][j]=0\n for x,y in [(1,0...
13
You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. N...
The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order.
Easy Python Solution : 🚀
find-all-groups-of-farmland
1
1
> ### Wherever you find an island compare all the coordinates of the island and store the minimum and maximum in an array.\n# Java Code\n---\n```\nclass Solution:\n def DFS(self,grid,i,j,visited,arr):\n if i<0 or i>=len(grid) or j<0 or j>=len(grid[0]) or visited[i][j] == True or grid[i][j] != 1:\n ...
3
You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. N...
The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order.
[Python3] dfs
find-all-groups-of-farmland
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/471dd5133055b331710ed3828849586ce1796b1a) for solutions of biweekly 60.\n```\nclass Solution:\n def findFarmland(self, land: List[List[int]]) -> List[List[int]]:\n m, n = len(land), len(land[0])\n ans = []\n for i in ra...
5
You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. N...
The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order.
Python3 simple flood fill dfs
find-all-groups-of-farmland
0
1
Mark cells as 0 as we find them and return the maximum coords we see (these are our bottom right coords). There are more efficient approaches but this template can be applied to a wider variety of problems with little modification.\n\n```python\ndef findFarmland(self, land: List[List[int]]) -> List[List[int]]:\n ...
1
You are given a **0-indexed** `m x n` binary matrix `land` where a `0` represents a hectare of forested land and a `1` represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist **entirely** of farmland. These rectangular areas are called **groups**. N...
The nodes with positive values are already in the correct order. Nodes with negative values need to be moved to the front. Nodes with negative values are in reversed order.
[Python3] tree traversal
operations-on-tree
0
1
Please check out this [commit](https://github.com/gaosanyong/leetcode/commit/471dd5133055b331710ed3828849586ce1796b1a) for solutions of biweekly 60.\n```\nclass LockingTree:\n\n def __init__(self, parent: List[int]):\n self.parent = parent\n self.tree = [[] for _ in parent]\n for i, x in enumera...
15
You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade node...
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
Intuitive Python with Comments
operations-on-tree
0
1
\n```\nclass LockingTree:\n \n def __init__(self, parent: List[int]):\n self.locked = {}\n self.parent = parent\n # Store immediate children of every node so we can DFS\n self.children = defaultdict(list)\n for i in range(len(parent)):\n par = parent[i]\n s...
0
You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade node...
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
Python 3: using dictionary and queue
operations-on-tree
0
1
Lock, Unlock -- Time: O(1)\nUpgrade -- Worst case Time: O(n)\n\n# Code\n```\nclass LockingTree:\n\n def __init__(self, parent: List[int]):\n self.parent = parent\n self.children = defaultdict(list)\n self.locked = {}\n for i, node in enumerate(parent):\n if i != -1:\n self.childre...
0
You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade node...
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
BFS Solution
operations-on-tree
0
1
# Code\n```python []\nclass LockingTree:\n\n def __init__(self, parent: List[int]):\n self.tree = parent\n self.vis = [0] * len(parent)\n self.child = defaultdict(list)\n for Child, Parent in enumerate(parent):\n if Child > 0: self.child[Parent].append(Child)\n\n def lock(se...
0
You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade node...
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
O(n) time | O(n) space | solution explained
operations-on-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse hashmap because its access and search time is O(1).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**init()**\n- declare an instance variable to store the parent array\n- set locked = a hashmap to store the lo...
0
You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade node...
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
Beats 100% TC || Python code
operations-on-tree
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 tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade node...
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
Python solution, laid out clearly
operations-on-tree
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 tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of the `ith` node. The root of the tree is node `0`, so `parent[0] = -1` since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade node...
Is there a way to iterate through all the subsets of the array? Can we use recursion to efficiently iterate through all the subsets?
[Python 3] Short, Neat
the-number-of-good-subsets
0
1
# Complexity\n- Time complexity: $O(N + 2^{30}) \\ \\ \\Big( = O(N + 2^{max(N) - min(N)}) \\Big)$\n * $N$ \u2014 gather frequences\n * $2^{30}$ \u2014 calculate all valid combinations\n\n- Space complexity: $O(N)$\n\n# Code\n```\nclass Solution:\n def numberOfGoodSubsets(self, nums: List[int]) -> int:\n MOD...
0
You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers. * For example, if `nums = [1, 2, 3, 4]`: * `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3...
Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.
Python | easy Solution | Faster than 99% | Bitmask |
the-number-of-good-subsets
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers. * For example, if `nums = [1, 2, 3, 4]`: * `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3...
Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.
DFS with prime factors without bitmasking
the-number-of-good-subsets
0
1
# Intuition\nThis can be solved by checking the common prime factors of the number from 2 to 30 since the upper bound is given upto 30\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI started with approach like this\nfor num 2 to 30 and not including bad numbers\nI collect their prime factors \...
0
You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers. * For example, if `nums = [1, 2, 3, 4]`: * `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3...
Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.
Python simple solution that beats 90%
the-number-of-good-subsets
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers. * For example, if `nums = [1, 2, 3, 4]`: * `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3...
Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.
100% Speee
the-number-of-good-subsets
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers. * For example, if `nums = [1, 2, 3, 4]`: * `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3...
Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.
Solution
the-number-of-good-subsets
1
1
```C++ []\nclass Solution {\npublic:\n long modulo = 1e9 + 7, result = 0;\n int primes[10] = {2,3,5,7,11,13,17,19,23,29};\n int nonprimes[8] = {6,10,14,15,21,22,26,30};\n int count[31];\n vector<int> bit_rep;\n long powerOfTwo(int x) {\n long result = 1;\n while(x--)result = (result * 2)...
0
You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers. * For example, if `nums = [1, 2, 3, 4]`: * `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3...
Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.
[Python3] dp
the-number-of-good-subsets
0
1
\nPlease check out this [commit](https://github.com/gaosanyong/leetcode/commit/471dd5133055b331710ed3828849586ce1796b1a) for solutions of biweekly 60.\n```\nclass Solution:\n def numberOfGoodSubsets(self, nums: List[int]) -> int:\n freq = [0] * 31\n for x in nums: freq[x] += 1\n \n masks ...
3
You are given an integer array `nums`. We call a subset of `nums` **good** if its product can be represented as a product of one or more **distinct prime** numbers. * For example, if `nums = [1, 2, 3, 4]`: * `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are **good** subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3...
Think about all valid strings of length n. Try to count the mismatched positions with each valid string of length n.
One line solution with using itertools.combinations
count-special-quadruplets
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 two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types: Implement the FindSumPairs class:
The length of nums1 is small in comparison to that of nums2 If we iterate over elements of nums1 we just need to find the count of tot - element for all elements in nums1
Heavy Brute Force---->Python
count-special-quadruplets
0
1
\n\n# 1. Brute Force\n```\nclass Solution:\n def countQuadruplets(self, nums: List[int]) -> int:\n count=0\n for a in range(len(nums)):\n for b in range(a+1,len(nums)):\n for c in range(b+1,len(nums)):\n for d in range(c+1,len(nums)):\n ...
4
You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types: Implement the FindSumPairs class:
The length of nums1 is small in comparison to that of nums2 If we iterate over elements of nums1 we just need to find the count of tot - element for all elements in nums1
✅ PYTHON || Simple 1-Liner 🔥
count-special-quadruplets
0
1
# Code\n```\nclass Solution:\n def countQuadruplets(self, nums: List[int]) -> int:\n return sum([1 for a, b, c, d in combinations(nums, 4) if a + b + c == d])\n```
2
You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types: Implement the FindSumPairs class:
The length of nums1 is small in comparison to that of nums2 If we iterate over elements of nums1 we just need to find the count of tot - element for all elements in nums1
Python, non-brute force. Time: O(N^2), Space: O(N^2)
count-special-quadruplets
0
1
```\nclass Solution:\n def countQuadruplets(self, nums: List[int]) -> int:\n idx = defaultdict(list)\n for i in range(len(nums)-1):\n for j in range(i+1, len(nums)):\n idx[nums[j]-nums[i]].append(i)\n \n count = 0 \n for i in range(len(nums)-3):\n ...
7
You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types: Implement the FindSumPairs class:
The length of nums1 is small in comparison to that of nums2 If we iterate over elements of nums1 we just need to find the count of tot - element for all elements in nums1
Python Solution Using SortedList Explained
the-number-of-weak-characters-in-the-game
0
1
# Intuition\nBasically we want to check for two properties for all possible pairs. This leads to O(N^2) which wont work. The idea is to sort the properties as per their attacks. This way we can eliminate the need to atleast check one of the properties due to its increasing order. Now we want to order out their defence....
1
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game. A character is said to be...
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
Python - Sort
the-number-of-weak-characters-in-the-game
0
1
**Solution 1:**\n\n```\nclass Solution:\n def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:\n \n properties.sort(key=lambda x: (-x[0],x[1]))\n \n ans = 0\n curr_max = 0\n \n for _, d in properties:\n if d < curr_max:\n ans...
215
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game. A character is said to be...
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
Python Easy Sorting Solution + Explanation + Runtime
the-number-of-weak-characters-in-the-game
0
1
# Explanation\n\nThis solution makes use of sorting the array with two keys. The first key, which takes priority, is the negative value of the `attack` of a given character. This causes the array to be sorted in descending value by attack. \n\nThe second key is used when the `attack` of two characters is equal (breakin...
45
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game. A character is said to be...
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
[Python3] Runtime: 1969 ms, faster than 99.62% | Memory: 65.7 MB, less than 98.32%
the-number-of-weak-characters-in-the-game
0
1
```\nclass Solution:\n def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:\n properties.sort(key=lambda x:(-x[0],x[1]))\n mxattack=properties[0][0]\n mxdefense=properties[0][1]\n count=0\n for i in range(1,len(properties)):\n if properties[i][0]<mxattac...
3
You are playing a game that contains multiple characters, and each of the characters has **two** main properties: **attack** and **defense**. You are given a 2D integer array `properties` where `properties[i] = [attacki, defensei]` represents the properties of the `ith` character in the game. A character is said to be...
Is there a way to build the solution from a base case? How many ways are there if we fix the position of one stick?
✔ Python3 Solution | DP
first-day-where-you-have-been-in-all-the-rooms
0
1
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def firstDayBeenInAllRooms(self, A):\n n = len(A)\n mod = 10 ** 9 + 7\n dp = [0] * (n)\n for e, i in enumerate(A[:-1], 1):\n dp[e] = dp[e - 1] + 1\n dp[e] = (2 *...
1
There are `n` rooms you need to visit, labeled from `0` to `n - 1`. Each day is labeled, starting from `0`. You will go in and visit one room a day. Initially on day `0`, you visit room `0`. The **order** you visit the rooms for the coming days is determined by the following **rules** and a given **0-indexed** array `...
Is it possible to swap one character in the first half of the palindrome to make the next one? Are there different cases for when the length is odd and even?