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
GCD && Median || C++ || Python || Greedy
make-k-subarray-sums-equal
0
1
# Intuition\nFor a simple problem of k==1, we need to make all elements equal to some number. That number will be median which can be understood with the help of number line and some intuition. For even length array n/2 and n/2+1 position both will give out same answer.\nSo now coming to this problem where we slide a k...
3
You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element. You can do the following operation any number of tim...
null
Python Union-Find without median or GCD
make-k-subarray-sums-equal
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n- starting from the question description, you may think of DP first. Good start but arr[i] is up to 10**9 so DP won\'t cut it. This pretty much means we have to find out mathematical/greedy way to solve it\n- then you make observation a...
0
You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element. You can do the following operation any number of tim...
null
Make all elements k apart equal with explanation in comments — O(N) time and space
make-k-subarray-sums-equal
0
1
# Approach\nSee comments\n\n# Complexity\nLet `N = len(arr)`\n- Time complexity: `O(N)`\nCalculating the gcd is `O(log(N))`.\nSum of `len(group)` for all groups is `N` since they contain each element once. Calculating median is `O(len(group))`, so the the entire loop is `O(N)`.\n\n- Space complexity: `O(N)`\nBecause we...
0
You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element. You can do the following operation any number of tim...
null
Simple Solution with Better Explanation
make-k-subarray-sums-equal
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- We have to restructure the array in such a way that it contains a pattern like, the element going out from the window is similar to the element comming into the window\n- (x, y, z, x, y, z, x, y, z) for window of size 3\n- pattern size...
0
You are given a **0-indexed** integer array `arr` and an integer `k`. The array `arr` is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element. You can do the following operation any number of tim...
null
question on a tricky test case
shortest-cycle-in-a-graph
0
1
The overall idea is to apply bfs, and viewed a cycle as two different paths starting from start, and merge at a common node. \n\nFor this test case\n[[0,3],[0,5],[3,4],[4,5],[1,9],[1,11],[9,10],[11,10],[2,6],[2,8],[6,7],[8,7],[0,1],[0,2],[1,2]]\n\nCan some one help explain why.. it forms a very special graph if you dra...
1
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1`. The edges in the graph are represented by a given 2D integer array `edges`, where `edges[i] = [ui, vi]` denotes an edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by at most one edge, and no...
null
[Python3] BFS from all nodes
shortest-cycle-in-a-graph
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/1dc118daa80cfe1161dcee412e7c3536970ca60d) for solutions of biweely 101. \n\n```\nclass Solution:\n def findShortestCycle(self, n: int, edges: List[List[int]]) -> int:\n graph = [[] for _ in range(n)]\n for u, v in edges: \n ...
5
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1`. The edges in the graph are represented by a given 2D integer array `edges`, where `edges[i] = [ui, vi]` denotes an edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by at most one edge, and no...
null
Python | BFS from All Vertices | O(VE)
shortest-cycle-in-a-graph
0
1
# Code\n```\nfrom collections import defaultdict\nfrom collections import deque\nclass Solution:\n def findShortestCycle(self, n: int, edges: List[List[int]]) -> int:\n G = defaultdict(list)\n for v, w in edges:\n G[v].append(w)\n G[w].append(v)\n self.res = float(\'inf\')\...
2
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1`. The edges in the graph are represented by a given 2D integer array `edges`, where `edges[i] = [ui, vi]` denotes an edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by at most one edge, and no...
null
[Java/Python 3] BFS within DFS.
shortest-cycle-in-a-graph
1
1
1. Construct a graph to access each edge by vertex efficiently;\n2. Traverse all vertices, for each one, `i`, initialize the `dist` all as `MX` value except for `i`, set it as `0`; initialize `parent` all as `-1`;\n3. Use BFS to find the shortest cycle through current vertex `i`: if any offspring of `i` has never been ...
10
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1`. The edges in the graph are represented by a given 2D integer array `edges`, where `edges[i] = [ui, vi]` denotes an edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by at most one edge, and no...
null
[Python 3] [NOT CORRECT] | Will update soon | Topological Sort | BFS
shortest-cycle-in-a-graph
0
1
```\nclass Solution:\n def findShortestCycle(self, n: int, edges: List[List[int]]) -> int:\n n = len(edges)\n g = defaultdict(list)\n indeg = Counter()\n inCycle = set(range(n))\n \n for i, j in edges:\n g[i].append(j)\n g[j].append(i)\n inde...
2
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1`. The edges in the graph are represented by a given 2D integer array `edges`, where `edges[i] = [ui, vi]` denotes an edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by at most one edge, and no...
null
Simple solution
shortest-cycle-in-a-graph
0
1
<!-- # Intuition -->\n<!-- - We have -->\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n<!-- # Approach\n- Fin -->\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 comple...
1
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1`. The edges in the graph are represented by a given 2D integer array `edges`, where `edges[i] = [ui, vi]` denotes an edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by at most one edge, and no...
null
[Python 3]DFS
shortest-cycle-in-a-graph
0
1
```\nclass Solution:\n def findShortestCycle(self, n: int, edges: List[List[int]]) -> int:\n \n g = defaultdict(list)\n \n for a, b in edges:\n g[a].append(b)\n g[b].append(a)\n \n self.vis = set()\n \n def dfs(node, par, path):\n ...
1
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1`. The edges in the graph are represented by a given 2D integer array `edges`, where `edges[i] = [ui, vi]` denotes an edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by at most one edge, and no...
null
💯✔ DAY 366 | [PYTHON/C++/JAVA] | EXPLAINED | algorithm || 100% BEATS
shortest-cycle-in-a-graph
1
1
# Please Upvote as it really motivates me\n##### \u2022\tThe problem statement is to find the length of the shortest cycle in an und graph. The approach used in this problem is to perform a breadth-first search (BFS) from each node in the graph and keep track of the distance from the starting node to each visited node....
6
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1`. The edges in the graph are represented by a given 2D integer array `edges`, where `edges[i] = [ui, vi]` denotes an edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by at most one edge, and no...
null
[Java/Python] | DFS | Runtime - 48ms
shortest-cycle-in-a-graph
1
1
1. Idea is to start traverse from each unvisited node and try to find shortest length cycle.\n2. Here we are using map to store Map<Node,[distance,status]> , status means whether this node is part of current dfs call or not.\n2. If we have cycle like this\n![image](https://assets.leetcode.com/users/images/89722531-69c2...
2
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1`. The edges in the graph are represented by a given 2D integer array `edges`, where `edges[i] = [ui, vi]` denotes an edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by at most one edge, and no...
null
Python3 Solution
shortest-cycle-in-a-graph
0
1
\n```\nclass Solution:\n def findShortestCycle(self, n: int, edges: List[List[int]]) -> int:\n G = [[] for _ in range(n)]\n for i, j in edges:\n G[i].append(j)\n G[j].append(i)\n def root(i):\n dis = [inf] * n\n fa = [-1] * n\n dis[i] = 0\n ...
1
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1`. The edges in the graph are represented by a given 2D integer array `edges`, where `edges[i] = [ui, vi]` denotes an edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by at most one edge, and no...
null
✅Python || Easy Approach
find-the-longest-balanced-substring-of-a-binary-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)$$ --...
3
You are given a binary string `s` consisting only of zeroes and ones. A substring of `s` is considered balanced if **all zeroes are before ones** and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring. Return _the length of the ...
null
Well Explained Easy Python 3 solution
find-the-longest-balanced-substring-of-a-binary-string
0
1
# Intuition\nTo find the longest balanced substring, we need to consider all possible substrings of the given binary string and check if each substring is balanced. To check if a substring is balanced, we need to count the number of zeroes and ones in the substring and check if they are equal. We can do this by maintai...
2
You are given a binary string `s` consisting only of zeroes and ones. A substring of `s` is considered balanced if **all zeroes are before ones** and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring. Return _the length of the ...
null
Python || Java || C++ || Implemetation
find-the-longest-balanced-substring-of-a-binary-string
1
1
**Just check or ```01```, ```0011```, ```000111```....**\n```C++ []\nclass Solution {\npublic:\n int findTheLongestBalancedSubstring(string s) {\n int res = 0;\n string temp = "01";\n while(temp.size() <= s.size()){\n if(s.find(temp) != string::npos) \n res = temp.size(...
97
You are given a binary string `s` consisting only of zeroes and ones. A substring of `s` is considered balanced if **all zeroes are before ones** and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring. Return _the length of the ...
null
simple python3 Solution T.C: O(N)
find-the-longest-balanced-substring-of-a-binary-string
0
1
T.C = O(n),where n is the len of the binary string\nS.C = O(1)\n```\nclass Solution:\n def findTheLongestBalancedSubstring(self, s: str) -> int:\n res = 0\n it = 0\n while it < len(s):\n oCnt ,zCnt = 0 , 0\n while it < len(s) and s[it] == "0" :\n zCnt += 1\n...
13
You are given a binary string `s` consisting only of zeroes and ones. A substring of `s` is considered balanced if **all zeroes are before ones** and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring. Return _the length of the ...
null
5 Lines of Code Super Logic with Python
find-the-longest-balanced-substring-of-a-binary-string
0
1
\n\n# Base Condition is the basic Logic\n```\nclass Solution:\n def findTheLongestBalancedSubstring(self, s: str) -> int:\n count,temp=0,"01"\n while len(temp)<=len(s):\n if temp in s:count=len(temp)\n temp="0"+temp+"1"\n return count\n```\n# please upvote me it would encou...
2
You are given a binary string `s` consisting only of zeroes and ones. A substring of `s` is considered balanced if **all zeroes are before ones** and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring. Return _the length of the ...
null
stack ||O(n)||Easy approach
find-the-longest-balanced-substring-of-a-binary-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)$$ --...
2
You are given a binary string `s` consisting only of zeroes and ones. A substring of `s` is considered balanced if **all zeroes are before ones** and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring. Return _the length of the ...
null
Python | Easy Solution✅
find-the-longest-balanced-substring-of-a-binary-string
0
1
# Code\n```\nclass Solution:\n def findTheLongestBalancedSubstring(self, s: str) -> int:\n maxx, zero_count, one_count = 0, 0, 0 \n for index, digit in enumerate(s):\n if digit == \'0\':\n if one_count:\n maxx = max(maxx,min(zero_count,one_count)* 2) \n ...
3
You are given a binary string `s` consisting only of zeroes and ones. A substring of `s` is considered balanced if **all zeroes are before ones** and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring. Return _the length of the ...
null
Soo simple.
find-the-longest-balanced-substring-of-a-binary-string
1
1
# Approach\nSimply traverse the string and count for the number of zeros and ones.\nAfter counting ones, reset the counters to 0.\nIf both (no. of zeros & no. of ones) are greater than zero, that means they are present.\nSome x no. of zeros followed by some y no. of ones.\nThis is to tackle cases like (11111)\nThen jus...
4
You are given a binary string `s` consisting only of zeroes and ones. A substring of `s` is considered balanced if **all zeroes are before ones** and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring. Return _the length of the ...
null
Python 3 || 5 lines, iteration, w/example || T/M: 100% / 100%
find-the-longest-balanced-substring-of-a-binary-string
0
1
```\nclass Solution:\n def findTheLongestBalancedSubstring(self, s: str) -> int:\n\n string = \'\' # Example: "01000111101"\n\n for i in range(25): # i string s \n # \u2013\u2013\u2013...
6
You are given a binary string `s` consisting only of zeroes and ones. A substring of `s` is considered balanced if **all zeroes are before ones** and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring. Return _the length of the ...
null
✅Python || Easy Approach || Dictionary
convert-an-array-into-a-2d-array-with-conditions
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
4
You are given an integer array `nums`. You need to create a 2D array from `nums` satisfying the following conditions: * The 2D array should contain **only** the elements of the array `nums`. * Each row in the 2D array contains **distinct** integers. * The number of rows in the 2D array should be **minimal**. Re...
null
O(N) Solution
convert-an-array-into-a-2d-array-with-conditions
0
1
# Summary\nIm sure there is a far better way to solve but I wasn\'t able to see any O(N) solutions available so decided to post. \n\n# Approach\nStep 1: Create a hashmap (mp1) to that maps elements of nums to their frequency and keep track of the maximum frequency (maxfreq). \n\nStep 2: Create another hashmap (mp2) th...
1
You are given an integer array `nums`. You need to create a 2D array from `nums` satisfying the following conditions: * The 2D array should contain **only** the elements of the array `nums`. * Each row in the 2D array contains **distinct** integers. * The number of rows in the 2D array should be **minimal**. Re...
null
[Python3] Hash Map/Counter - O(n * max(frequency) time, O(1) space
convert-an-array-into-a-2d-array-with-conditions
0
1
# Intuition\nWe create the 2D array map with the number of subarrays equal to max frequency that a number in `nums` can occur, representing the minimum rows that we have to have since we must have unique numbers in each row. For example, if the array is `[1,3,4,1,2,3,1]`, we must have at least 3 rows to accommodate all...
1
You are given an integer array `nums`. You need to create a 2D array from `nums` satisfying the following conditions: * The 2D array should contain **only** the elements of the array `nums`. * Each row in the 2D array contains **distinct** integers. * The number of rows in the 2D array should be **minimal**. Re...
null
python3 Solution
convert-an-array-into-a-2d-array-with-conditions
0
1
\n```\nclass Solution:\n def findMatrix(self, nums: List[int]) -> List[List[int]]:\n ans=[]\n count=Counter(nums)\n while count:\n val=[]\n drop=[]\n for k,v in count.items():\n val.append(k)\n count[k]-=1\n if count[k...
1
You are given an integer array `nums`. You need to create a 2D array from `nums` satisfying the following conditions: * The 2D array should contain **only** the elements of the array `nums`. * Each row in the 2D array contains **distinct** integers. * The number of rows in the 2D array should be **minimal**. Re...
null
Using Dictionaries Logic
convert-an-array-into-a-2d-array-with-conditions
0
1
\n# 1.Main Logic is Finding max Frequency\n```\nclass Solution:\n def findMatrix(self, nums: List[int]) -> List[List[int]]:\n dic=Counter(nums)\n list2=[]\n for i in range(max(dic.values())):\n list1=[]\n for key,freq in dic.items():\n if freq!=0:\n ...
3
You are given an integer array `nums`. You need to create a 2D array from `nums` satisfying the following conditions: * The 2D array should contain **only** the elements of the array `nums`. * Each row in the 2D array contains **distinct** integers. * The number of rows in the 2D array should be **minimal**. Re...
null
Simple solution
convert-an-array-into-a-2d-array-with-conditions
0
1
# Code\n```\nclass Solution:\n def findMatrix(self, nums: List[int]) -> List[List[int]]:\n output = []\n\n while len(nums):\n output.append(list(set(nums)))\n for i in output[-1]:\n nums.pop(nums.index(i))\n \n return output\n```
1
You are given an integer array `nums`. You need to create a 2D array from `nums` satisfying the following conditions: * The 2D array should contain **only** the elements of the array `nums`. * Each row in the 2D array contains **distinct** integers. * The number of rows in the 2D array should be **minimal**. Re...
null
Python3 | One-liner
convert-an-array-into-a-2d-array-with-conditions
0
1
```\nclass Solution:\n def findMatrix(self, nums: List[int]) -> List[List[int]]:\n return [[x for x in arr if x] for arr in zip_longest(*[(n,)*f for n, f in Counter(nums).items()], fillvalue=0)]\n```
1
You are given an integer array `nums`. You need to create a 2D array from `nums` satisfying the following conditions: * The 2D array should contain **only** the elements of the array `nums`. * Each row in the 2D array contains **distinct** integers. * The number of rows in the 2D array should be **minimal**. Re...
null
Python3 Set
convert-an-array-into-a-2d-array-with-conditions
0
1
\n\n# Complexity \n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findMatrix(self, nums: List[int]) -> List[List[int]]:\n res = []\n while len(nums) ...
1
You are given an integer array `nums`. You need to create a 2D array from `nums` satisfying the following conditions: * The 2D array should contain **only** the elements of the array `nums`. * Each row in the 2D array contains **distinct** integers. * The number of rows in the 2D array should be **minimal**. Re...
null
✅Python || Easy Approach || Diff
mice-and-cheese
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
There are two mice and `n` different types of cheese, each type of cheese should be eaten by exactly one mouse. A point of the cheese with index `i` (**0-indexed**) is: * `reward1[i]` if the first mouse eats it. * `reward2[i]` if the second mouse eats it. You are given a positive integer array `reward1`, a posit...
null
Python max heap O(nlogn)
mice-and-cheese
0
1
```\nclass Solution:\n def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int:\n \n #build max heap, based on the extra we can get if we \n #choose reward1\n heap = []\n for i in range(0,len(reward1)):\n heap.append( [ -reward1[i]+reward2[i] ,i ]...
1
There are two mice and `n` different types of cheese, each type of cheese should be eaten by exactly one mouse. A point of the cheese with index `i` (**0-indexed**) is: * `reward1[i]` if the first mouse eats it. * `reward2[i]` if the second mouse eats it. You are given a positive integer array `reward1`, a posit...
null
Python || sort || O(n log n)
mice-and-cheese
0
1
1. The first mice will eat exactly `k` types, and the second mice will eat others.\n2. Sort `reward1 - reward2` in descending order. Let the first mice eat those types with highest difference.\n```\nclass Solution:\n def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int:\n diff = [[re...
3
There are two mice and `n` different types of cheese, each type of cheese should be eaten by exactly one mouse. A point of the cheese with index `i` (**0-indexed**) is: * `reward1[i]` if the first mouse eats it. * `reward2[i]` if the second mouse eats it. You are given a positive integer array `reward1`, a posit...
null
Streaming Solution Explained | No Sorting | O(N log k)
mice-and-cheese
0
1
# Intuition\nThe most important thing that matters is the advantage $$r_1[i]-r_2[i]$$ (the difference of rewards for mouse 1 and 2 respectively). We want to give mouse 1 the cheese whenever it has the greatest advantage and mouse 2 the cheese whenever it has greatest advantage. \n\n# Sorting Solution\n\nOne way to do t...
1
There are two mice and `n` different types of cheese, each type of cheese should be eaten by exactly one mouse. A point of the cheese with index `i` (**0-indexed**) is: * `reward1[i]` if the first mouse eats it. * `reward2[i]` if the second mouse eats it. You are given a positive integer array `reward1`, a posit...
null
Python Heap | In-depth Explanation
mice-and-cheese
0
1
\n\nWe want to maximize the total reward by selecting \'k\' values from reward1 and everything remaining from reward2. To achieve this, we need to carefully choose values from reward1, as selecting an index in reward1 will make that index unavailable in reward2.\n\nTo determine the best selection, we first calculate th...
11
There are two mice and `n` different types of cheese, each type of cheese should be eaten by exactly one mouse. A point of the cheese with index `i` (**0-indexed**) is: * `reward1[i]` if the first mouse eats it. * `reward2[i]` if the second mouse eats it. You are given a positive integer array `reward1`, a posit...
null
Python3 | BFS w/o a queue beats 100% time and memory (Index math explained)
minimum-reverse-operations
0
1
# Index math\n\nA length-$N$ list has $N-k+1$ length-$k$ slices, one starting at each $i \\in [0, N-k]$.\n\nSuppose the set/on/one bit is currenlty at position $p \\in [0, N)$. Reverseing one of these slices, `bits[i:i+k]`, has no effect. if $p < i$ or $p \\geq i+k$; we should only consider reversing slices `bits[i:i+k...
1
You are given an integer `n` and an integer `p` in the range `[0, n - 1]`. Representing a **0-indexed** array `arr` of length `n` where all positions are set to `0`'s, except position `p` which is set to `1`. You are also given an integer array `banned` containing some positions from the array. For the **i****th** pos...
null
[Python3] BFS + SortedList, keep track of remaining nodes
minimum-reverse-operations
0
1
Evidently, we should start our investigation with the question: if there is a `1` at position `node`, what neighboring nodes `nei` could it reach in one move?\n\nLet `i_left = max(0, node - K + 1)`, `i_right = min(node + K - 1, n - 1) - (K - 1)` be the starting positions of the subarray to be reversed. Then, after rev...
35
You are given an integer `n` and an integer `p` in the range `[0, n - 1]`. Representing a **0-indexed** array `arr` of length `n` where all positions are set to `0`'s, except position `p` which is set to `1`. You are also given an integer array `banned` containing some positions from the array. For the **i****th** pos...
null
Python3 Solution
minimum-reverse-operations
0
1
# Intuition\nThis problem was hard to understand, and it has an $$O(K * N)$$ issue that needs to be addressed.\n\n# Approach\nThe basic algorithm is a breadth-first search of positions, where depth is a reversal operation.\n* Avoid set lookups by marking `banned` positions with a `-2` reduces the constant coefficient...
11
You are given an integer `n` and an integer `p` in the range `[0, n - 1]`. Representing a **0-indexed** array `arr` of length `n` where all positions are set to `0`'s, except position `p` which is set to `1`. You are also given an integer array `banned` containing some positions from the array. For the **i****th** pos...
null
Python || BFS, binary search || O(n log n)
minimum-reverse-operations
0
1
1. Suppose we stand at `i1`, the widest range we can reach by one reverse is `i1-k+1`, `i1-k+3`, ..., `i1+k-3`, `i1+k-1`. The indices in the sequence are all even or all odd. \nBut we should be cautious when `i1 < k` or `i1 > n-k`. The starting index of the leftmost subarray containing `i1` is `max(0, i1-k+1)`, while t...
2
You are given an integer `n` and an integer `p` in the range `[0, n - 1]`. Representing a **0-indexed** array `arr` of length `n` where all positions are set to `0`'s, except position `p` which is set to `1`. You are also given an integer array `banned` containing some positions from the array. For the **i****th** pos...
null
[Python] Simple approach with SortedList + comments
minimum-reverse-operations
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is formulated as a graph exploration problem, and the answer can be found by using BFS\n\nThe first complex issue is finding out to which other nodes I can go from a given node and a given k. Let\'s ignore cases too close to t...
0
You are given an integer `n` and an integer `p` in the range `[0, n - 1]`. Representing a **0-indexed** array `arr` of length `n` where all positions are set to `0`'s, except position `p` which is set to `1`. You are also given an integer array `banned` containing some positions from the array. For the **i****th** pos...
null
Minimum Reverse Operations to Move a Value in an Array
minimum-reverse-operations
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is asking us to find the minimum number of reverse operations needed to move a value (represented as 1) to each position in an array, given certain positions are banned. The reverse operation can only be performed on a subarra...
0
You are given an integer `n` and an integer `p` in the range `[0, n - 1]`. Representing a **0-indexed** array `arr` of length `n` where all positions are set to `0`'s, except position `p` which is set to `1`. You are also given an integer array `banned` containing some positions from the array. For the **i****th** pos...
null
Doubly linked list, python
minimum-reverse-operations
0
1
\n# Code\n```\nclass Solution:\n def minReverseOperations(self, n: int, p: int, banned: List[int], k: int) -> List[int]:\n right = [(i+2) % (n+4) for i in range(n+4)]\n left = [(i-2) for i in range(n+4)]\n distance = [-1] * n\n q = collections.deque(maxlen=n)\n\n def first(i):\n ...
0
You are given an integer `n` and an integer `p` in the range `[0, n - 1]`. Representing a **0-indexed** array `arr` of length `n` where all positions are set to `0`'s, except position `p` which is set to `1`. You are also given an integer array `banned` containing some positions from the array. For the **i****th** pos...
null
[Python] Beats 100% time with 14 lines, simple BFS idea
minimum-reverse-operations
0
1
# Intuition\n\nSome observations about the problem:\n\n* Each subarray reverse operation is just moving the position p of the single 1 in the array.\n* Therefore the current "state" after any number of reverses can be summarized by the current position `pos` of the 1, and the number of `moves` taken to get there.\n...
0
You are given an integer `n` and an integer `p` in the range `[0, n - 1]`. Representing a **0-indexed** array `arr` of length `n` where all positions are set to `0`'s, except position `p` which is set to `1`. You are also given an integer array `banned` containing some positions from the array. For the **i****th** pos...
null
[Python3] Without The Use Of Imports
minimum-reverse-operations
0
1
# Intuition\nI didn\'t really like how every other solution I saw involved some third party packages. I wanted to write a piece of code that works with python3 out of the box, no other packages or libraries.\n\n# Approach\nThe big piece I was missing was two fold:\n\n1. BFS alone is not fast enough. You need to track a...
0
You are given an integer `n` and an integer `p` in the range `[0, n - 1]`. Representing a **0-indexed** array `arr` of length `n` where all positions are set to `0`'s, except position `p` which is set to `1`. You are also given an integer array `banned` containing some positions from the array. For the **i****th** pos...
null
Python (Simple BFS)
minimum-reverse-operations
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 `n` and an integer `p` in the range `[0, n - 1]`. Representing a **0-indexed** array `arr` of length `n` where all positions are set to `0`'s, except position `p` which is set to `1`. You are also given an integer array `banned` containing some positions from the array. For the **i****th** pos...
null
Python3 - Optimized BFS Algorithm
minimum-reverse-operations
0
1
\n# Code\n```\nfrom bisect import bisect_left, bisect_right\nfrom collections import deque\n\nclass Solution:\n def minReverseOperations(self, n, p, banned_vals, K):\n remaining = [[], []]\n banned = set(banned_vals)\n for u in range(n):\n if u != p and u not in banned:\n ...
0
You are given an integer `n` and an integer `p` in the range `[0, n - 1]`. Representing a **0-indexed** array `arr` of length `n` where all positions are set to `0`'s, except position `p` which is set to `1`. You are also given an integer array `banned` containing some positions from the array. For the **i****th** pos...
null
Python Elegant & Short | RegEx
number-of-valid-clock-times
0
1
```\nimport re\n\n\nclass Solution:\n """\n Time: O(1)\n Memory: O(1)\n """\n\n def countTime(self, time: str) -> int:\n pattern = time.replace(\'?\', \'.\')\n return sum(\n re.fullmatch(pattern, f\'{hour:02}:{minute:02}\') is not None\n for hour in range(24)\n ...
34
You are given a string of length `5` called `time`, representing the current time on a digital clock in the format `"hh:mm "`. The **earliest** possible time is `"00:00 "` and the **latest** possible time is `"23:59 "`. In the string `time`, the digits represented by the `?` symbol are **unknown**, and must be **repla...
null
Structural pattern matching
number-of-valid-clock-times
0
1
Minutes are easy. For hours, we there could be be 1, 2, 3, 4, 10 or 24 combinations.\n\n**Python 3**\nJust for fun - using structural pattern matching.\n```python\nclass Solution:\n def countTime(self, t: str) -> int:\n mm = (6 if t[3] == \'?\' else 1) * (10 if t[4] == \'?\' else 1)\n match [t[0], t[1]...
25
You are given a string of length `5` called `time`, representing the current time on a digital clock in the format `"hh:mm "`. The **earliest** possible time is `"00:00 "` and the **latest** possible time is `"23:59 "`. In the string `time`, the digits represented by the `?` symbol are **unknown**, and must be **repla...
null
beats 97.60%
number-of-valid-clock-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)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given a string of length `5` called `time`, representing the current time on a digital clock in the format `"hh:mm "`. The **earliest** possible time is `"00:00 "` and the **latest** possible time is `"23:59 "`. In the string `time`, the digits represented by the `?` symbol are **unknown**, and must be **repla...
null
Understandable If-Else python solution
number-of-valid-clock-times
0
1
```\nclass Solution:\n def countTime(self, time: str) -> int:\n res = 1\n\t\t# split hour and minute digits\n h1, h2, _ , m1, m2 = time\n \n if h1 == "?" and h2 == "?":\n res*=24\n elif h1 == "?":\n if int(h2) >=4:\n res*=2\n else:\n...
10
You are given a string of length `5` called `time`, representing the current time on a digital clock in the format `"hh:mm "`. The **earliest** possible time is `"00:00 "` and the **latest** possible time is `"23:59 "`. In the string `time`, the digits represented by the `?` symbol are **unknown**, and must be **repla...
null
Python | Prefix Product
range-product-queries-of-powers
0
1
```\nclass Solution:\n def productQueries(self, n: int, queries: List[List[int]]) -> List[int]:\n MOD = (10**9)+7\n binary = bin(n)[2:]\n powers = []\n result = []\n for index, val in enumerate(binary[::-1]):\n if val == "1":\n powers.append(2**index)\n ...
8
Given a positive integer `n`, there exists a **0-indexed** array called `powers`, composed of the **minimum** number of powers of `2` that sum to `n`. The array is sorted in **non-decreasing** order, and there is **only one** way to form the array. You are also given a **0-indexed** 2D integer array `queries`, where `...
null
Compute set bit power's
range-product-queries-of-powers
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nAs we\'ll know, we can any represent in it\'s power of 2\'s. \nHow to find which power of 2\'s is exactly required?\nChange the number to binary and the only the set-bit position will contribute to power. \nSo, Precompute all the required power. Here ...
1
Given a positive integer `n`, there exists a **0-indexed** array called `powers`, composed of the **minimum** number of powers of `2` that sum to `n`. The array is sorted in **non-decreasing** order, and there is **only one** way to form the array. You are also given a **0-indexed** 2D integer array `queries`, where `...
null
Python Elegant & Short | Prefix Sum | Binary Power
range-product-queries-of-powers
0
1
```\nfrom itertools import accumulate\nfrom typing import List, Generator\n\n\nclass Solution:\n """\n Time: O(log(n) + m)\n Memory: O(log(n))\n\n where m - length of queries\n """\n\n MAX_POWER = 32\n MOD = 10 ** 9 + 7\n\n def productQueries(self, n: int, queries: List[List[int]]) -> List[int...
11
Given a positive integer `n`, there exists a **0-indexed** array called `powers`, composed of the **minimum** number of powers of `2` that sum to `n`. The array is sorted in **non-decreasing** order, and there is **only one** way to form the array. You are also given a **0-indexed** 2D integer array `queries`, where `...
null
✔ Python3 Solution | Prefix Sum | 2 Line Solution
range-product-queries-of-powers
0
1
```\nclass Solution:\n def productQueries(self, n, Q):\n A = list(accumulate([i for i in range(31) if n & (1 << i)])) + [0]\n return [pow(2, A[r] - A[l - 1], 10 ** 9 + 7) for l, r in Q]\n```
2
Given a positive integer `n`, there exists a **0-indexed** array called `powers`, composed of the **minimum** number of powers of `2` that sum to `n`. The array is sorted in **non-decreasing** order, and there is **only one** way to form the array. You are also given a **0-indexed** 2D integer array `queries`, where `...
null
fast python solution
range-product-queries-of-powers
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:log(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:log(n)\n<!-- Add your space complexity here, e.g....
5
Given a positive integer `n`, there exists a **0-indexed** array called `powers`, composed of the **minimum** number of powers of `2` that sum to `n`. The array is sorted in **non-decreasing** order, and there is **only one** way to form the array. You are also given a **0-indexed** 2D integer array `queries`, where `...
null
Product prefix O(1) query / Product Segment tree O(logn) query
range-product-queries-of-powers
0
1
# Intuition\nThe problem is composed of two main parts:\n1. **Q1** determine which are the minimum powers of 2 which can be used to represents the given number N\n2. **Q2** compose an array created in increasing order of those powers\n3. **Q3** find product of values in the given query range relative to the previously ...
2
Given a positive integer `n`, there exists a **0-indexed** array called `powers`, composed of the **minimum** number of powers of `2` that sum to `n`. The array is sorted in **non-decreasing** order, and there is **only one** way to form the array. You are also given a **0-indexed** 2D integer array `queries`, where `...
null
python || easy soln
range-product-queries-of-powers
0
1
```\nclass Solution:\n def productQueries(self, n: int, queries: List[List[int]]) -> List[int]:\n def min_arr(x):\n k = bin(x)[2:]\n k = k[::-1]\n ans = []\n for i in range(0, len(k)):\n if (k[i] == \'1\'):\n ans.append(2**i)\n ...
1
Given a positive integer `n`, there exists a **0-indexed** array called `powers`, composed of the **minimum** number of powers of `2` that sum to `n`. The array is sorted in **non-decreasing** order, and there is **only one** way to form the array. You are also given a **0-indexed** 2D integer array `queries`, where `...
null
Python solution
minimize-maximum-of-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe previous element takes the fall for the bigger element.\nThe elements are getting equally distributed in a order.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCalculated average sum for every element in the ...
1
You are given a **0-indexed** array `nums` comprising of `n` non-negative integers. In one operation, you must: * Choose an integer `i` such that `1 <= i < n` and `nums[i] > 0`. * Decrease `nums[i]` by 1. * Increase `nums[i - 1]` by 1. Return _the **minimum** possible value of the **maximum** integer of_ `nums...
null
Python3 O(n) greedy solution.
minimize-maximum-of-array
0
1
# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def minimizeArrayValue(self, nums: List[int]) -> int:\n max_val = cur_sum = 0\n\n for ind, num in enumerate(nums): \n cur_sum += num\n\n if num > max_val:\n ...
1
You are given a **0-indexed** array `nums` comprising of `n` non-negative integers. In one operation, you must: * Choose an integer `i` such that `1 <= i < n` and `nums[i] > 0`. * Decrease `nums[i]` by 1. * Increase `nums[i - 1]` by 1. Return _the **minimum** possible value of the **maximum** integer of_ `nums...
null
Python shortest 1-liner. Beats 100%. Functional programming.
minimize-maximum-of-array
0
1
# Approach\nTL;DR, Same as [Editorial Solution](https://leetcode.com/problems/minimize-maximum-of-array/editorial/) written in functional approach.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\nwhere, `n is length of nums`.\n\n# Code\n```python\nclass Solution:\n def minimizeArrayVa...
2
You are given a **0-indexed** array `nums` comprising of `n` non-negative integers. In one operation, you must: * Choose an integer `i` such that `1 <= i < n` and `nums[i] > 0`. * Decrease `nums[i]` by 1. * Increase `nums[i - 1]` by 1. Return _the **minimum** possible value of the **maximum** integer of_ `nums...
null
✅✅Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand🔥
minimize-maximum-of-array
1
1
# Please UPVOTE \uD83D\uDC4D\n\n**!! BIG ANNOUNCEMENT !!**\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers this week. I planned to give for next 10,000 Subscribers a...
126
You are given a **0-indexed** array `nums` comprising of `n` non-negative integers. In one operation, you must: * Choose an integer `i` such that `1 <= i < n` and `nums[i] > 0`. * Decrease `nums[i]` by 1. * Increase `nums[i - 1]` by 1. Return _the **minimum** possible value of the **maximum** integer of_ `nums...
null
Image Explanation🏆- [Brute -> Better O(nlogM) -> Optimal O(n) ] - C++/Java/Python
minimize-maximum-of-array
1
1
# Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`Reducing Dishes` by `Aryan Mittal`\n![lc.png](https://assets.leetcode.com/users/images/c847042a-0467-4a70-ae8e-2334f4f324f8_1680662519.7955203.png)\n\n\n# Approach & Intution\n![image.png](https://assets.leetcode.com/users/images/12bc569d-cd92-4670-b3d4-f7f...
182
You are given a **0-indexed** array `nums` comprising of `n` non-negative integers. In one operation, you must: * Choose an integer `i` such that `1 <= i < n` and `nums[i] > 0`. * Decrease `nums[i]` by 1. * Increase `nums[i - 1]` by 1. Return _the **minimum** possible value of the **maximum** integer of_ `nums...
null
✔💯 DAY 370 | [JAVA/C++/PYTHON] | EXPLAINED |INTUITION | Approach | PROOF
minimize-maximum-of-array
1
1
\n![image.png](https://assets.leetcode.com/users/images/025d868a-77e4-4618-80f8-194a954ed596_1680671235.2830439.png)\n\n# Please Upvote as it really motivates me\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n##### \u2022\tTo find the minimum maximum value of an array, we can use an ...
13
You are given a **0-indexed** array `nums` comprising of `n` non-negative integers. In one operation, you must: * Choose an integer `i` such that `1 <= i < n` and `nums[i] > 0`. * Decrease `nums[i]` by 1. * Increase `nums[i - 1]` by 1. Return _the **minimum** possible value of the **maximum** integer of_ `nums...
null
[Python3] post-order dfs
create-components-with-same-value
0
1
Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/b09317beeb5fa2ae0b6d2537172ab52647a75cea) for solutions of biweekly 89. \n\n```\nclass Solution:\n def componentValue(self, nums: List[int], edges: List[List[int]]) -> int:\n tree = [[] for _ in nums]\n for u, v in edges: \n ...
12
There is an undirected tree with `n` nodes labeled from `0` to `n - 1`. You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge be...
null
[Python] Get factors of sum all nodes then check
create-components-with-same-value
0
1
# Intuition\n- Sum of each connected component must be values in factors of `sum(nums)`, and at least `max(nums)`.\n- So get factors of sum all nodes then check if we can split into connected component, where sum of each connected component is equal to factor.\n\n# Complexity\n- Time complexity: `O(sqrt(SUM_ALL_NODE) +...
4
There is an undirected tree with `n` nodes labeled from `0` to `n - 1`. You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge be...
null
Python (Simple DFS)
create-components-with-same-value
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 an undirected tree with `n` nodes labeled from `0` to `n - 1`. You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge be...
null
Python | Sorting + Two Pointers approach | 99.66% faster ✅
largest-positive-integer-that-exists-with-its-negative
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach: Two Pointers, Sorting\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n logn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your s...
1
Given an integer array `nums` that **does not contain** any zeros, find **the largest positive** integer `k` such that `-k` also exists in the array. Return _the positive integer_ `k`. If there is no such integer, return `-1`. **Example 1:** **Input:** nums = \[-1,2,-3,3\] **Output:** 3 **Explanation:** 3 is the onl...
null
largest-positive-integer-that-exists-with-its-negative
largest-positive-integer-that-exists-with-its-negative
0
1
\n\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n\n\n# Code\n```\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n nums=sorted(nums,reverse=True)\n s=set(nums)\n for i in range(len(nums)):\n if 0-nums[i] in s:\n return nums[i]\n return -1\n\n```
1
Given an integer array `nums` that **does not contain** any zeros, find **the largest positive** integer `k` such that `-k` also exists in the array. Return _the positive integer_ `k`. If there is no such integer, return `-1`. **Example 1:** **Input:** nums = \[-1,2,-3,3\] **Output:** 3 **Explanation:** 3 is the onl...
null
Beginner-friendly || Simple solution with HashMap
largest-positive-integer-that-exists-with-its-negative
0
1
# Intuition\nLet\'s briefly explain, what problem is:\n- there\'s a list of `nums`\n- our goal is to find **the maximum**, that has a **negative integer of himself** (i.e., 2 and -2 etc)\n\nThe approach is **straighforward**: iterate over `nums` and at each step check, if a particular integer is **a maximum one**, and ...
2
Given an integer array `nums` that **does not contain** any zeros, find **the largest positive** integer `k` such that `-k` also exists in the array. Return _the positive integer_ `k`. If there is no such integer, return `-1`. **Example 1:** **Input:** nums = \[-1,2,-3,3\] **Output:** 3 **Explanation:** 3 is the onl...
null
simple solution for beginners
count-number-of-distinct-integers-after-reverse-operations
0
1
\n# Code\n```\nclass Solution:\n def countDistinctIntegers(self, nums: List[int]) -> int:\n #copy the list to the variable num\n num=nums.copy()\n #reverse all the elements in nums and store it in the num list\n for x in nums:\n sum=0\n while x>0:\n di...
1
You are given an array `nums` consisting of **positive** integers. You have to take each integer in the array, **reverse its digits**, and add it to the end of the array. You should apply this operation to the original integers in `nums`. Return _the number of **distinct** integers in the final array_. **Example 1:*...
null
SIMPLE SOLUTION || T/S: O (N)/O(N)
count-number-of-distinct-integers-after-reverse-operations
0
1
```\nclass Solution:\n def countDistinctIntegers(self, nums: List[int]) -> int:\n dct=defaultdict(lambda :0)\n for num in nums:\n dct[num]=1\n for num in nums:\n rev=int(str(num)[::-1])\n if dct[rev]!=1:\n dct[rev]=1\n return len(dct)\n```
1
You are given an array `nums` consisting of **positive** integers. You have to take each integer in the array, **reverse its digits**, and add it to the end of the array. You should apply this operation to the original integers in `nums`. Return _the number of **distinct** integers in the final array_. **Example 1:*...
null
Python BEATS 99.05% Easy
count-number-of-distinct-integers-after-reverse-operations
0
1
\n```\nclass Solution:\n def countDistinctIntegers(self, nums: List[int]) -> int:\n l=[]\n for i in nums:\n l.append(int(str(i)[::-1]))\n nums+=l\n #print(nums)\n return len(set(nums))\n```
2
You are given an array `nums` consisting of **positive** integers. You have to take each integer in the array, **reverse its digits**, and add it to the end of the array. You should apply this operation to the original integers in `nums`. Return _the number of **distinct** integers in the final array_. **Example 1:*...
null
✅✅✅ 90 % faster and one-line solution
count-number-of-distinct-integers-after-reverse-operations
0
1
![Screenshot 2023-01-04 at 10.48.34.png](https://assets.leetcode.com/users/images/7271fb8f-74f9-4b99-9727-e569f35a2b82_1672811515.2733319.png)\n\n```\nclass Solution:\n def countDistinctIntegers(self, nums: List[int]) -> int:\n return len(set([int(str(n)[::-1]) for n in nums] + nums))\n```
1
You are given an array `nums` consisting of **positive** integers. You have to take each integer in the array, **reverse its digits**, and add it to the end of the array. You should apply this operation to the original integers in `nums`. Return _the number of **distinct** integers in the final array_. **Example 1:*...
null
Easy Simple Approach In Python
count-number-of-distinct-integers-after-reverse-operations
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\niterate over the given list and convert in string reverse it and add it end of the array if leading zeroes are present we used lstrip function to remove all the front zero.\n\n# Complexity\n- Time complexity:\n<!-- Add your ...
1
You are given an array `nums` consisting of **positive** integers. You have to take each integer in the array, **reverse its digits**, and add it to the end of the array. You should apply this operation to the original integers in `nums`. Return _the number of **distinct** integers in the final array_. **Example 1:*...
null
sum-of-number-and-its-reverse
sum-of-number-and-its-reverse
0
1
\n\n# Code\n```\nclass Solution:\n def sumOfNumberAndReverse(self, num: int) -> bool:\n i=1\n if num==0:\n return True\n while i<num:\n a=str(i)\n a=a[::-1]\n a=int(a)\n if a+i==num:\n return True\n i+=1\n re...
1
Given a **non-negative** integer `num`, return `true` _if_ `num` _can be expressed as the sum of any **non-negative** integer and its reverse, or_ `false` _otherwise._ **Example 1:** **Input:** num = 443 **Output:** true **Explanation:** 172 + 271 = 443 so we return true. **Example 2:** **Input:** num = 63 **Output...
null
[Python3] Little Math, Time and Space: O(1)
sum-of-number-and-its-reverse
0
1
Probably could be optimized better and generalized to arbitrary length (or value)\n```python\nclass Solution:\n def sumOfNumberAndReverse(self, num: int) -> bool:\n if num <= 18:\n\t\t #Adding 1 digit number, a, and its reverse, also a: 2a\n if num % 2 == 0:\n return True\n\t\t\t#A...
1
Given a **non-negative** integer `num`, return `true` _if_ `num` _can be expressed as the sum of any **non-negative** integer and its reverse, or_ `false` _otherwise._ **Example 1:** **Input:** num = 443 **Output:** true **Explanation:** 172 + 271 = 443 so we return true. **Example 2:** **Input:** num = 63 **Output...
null
Detailed explanation of Python O(n) solution
count-subarrays-with-fixed-bounds
0
1
# Intuition\nWe have to count all subarrays with certain properties. In such problems, a good pattern is to think about what happens when the subarrays end at a certain position. Let\'s iterate through the array and think about how to calculate the number of appropriate subarrays that end at a current position.\n\nnums...
2
You are given an integer array `nums` and two integers `minK` and `maxK`. A **fixed-bound subarray** of `nums` is a subarray that satisfies the following conditions: * The **minimum** value in the subarray is equal to `minK`. * The **maximum** value in the subarray is equal to `maxK`. Return _the **number** of f...
null
Awesome Logic Beginner Friendy Code in python
count-subarrays-with-fixed-bounds
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 integer array `nums` and two integers `minK` and `maxK`. A **fixed-bound subarray** of `nums` is a subarray that satisfies the following conditions: * The **minimum** value in the subarray is equal to `minK`. * The **maximum** value in the subarray is equal to `maxK`. Return _the **number** of f...
null
Formula based Problem
count-subarrays-with-fixed-bounds
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 integer array `nums` and two integers `minK` and `maxK`. A **fixed-bound subarray** of `nums` is a subarray that satisfies the following conditions: * The **minimum** value in the subarray is equal to `minK`. * The **maximum** value in the subarray is equal to `maxK`. Return _the **number** of f...
null
📌📌Python3 || ⚡819 ms, faster than 97.11% of Python3
count-subarrays-with-fixed-bounds
0
1
![image](https://assets.leetcode.com/users/images/4fc8bf84-0bf6-448a-8f87-e11ac634dfd6_1677915439.91398.png)\n```\ndef countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:\n count = last = 0\n min_index = max_index = -1\n for i, num in enumerate(nums):\n if num < minK or n...
2
You are given an integer array `nums` and two integers `minK` and `maxK`. A **fixed-bound subarray** of `nums` is a subarray that satisfies the following conditions: * The **minimum** value in the subarray is equal to `minK`. * The **maximum** value in the subarray is equal to `maxK`. Return _the **number** of f...
null
Reverse Select - beating 100% in time
count-subarrays-with-fixed-bounds
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCalculating the count of subarrays qualified is harder than calculating the opposite. Then do the opposite and subtract it from number of all possible subarrays.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWhen...
1
You are given an integer array `nums` and two integers `minK` and `maxK`. A **fixed-bound subarray** of `nums` is a subarray that satisfies the following conditions: * The **minimum** value in the subarray is equal to `minK`. * The **maximum** value in the subarray is equal to `maxK`. Return _the **number** of f...
null
✅Python3 simple solution O(N)🔥🔥
count-subarrays-with-fixed-bounds
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Sliding window/two pointer method.**\n![Screenshot 2023-03-04 191026.png](https://assets.leetcode.com/users/images/dee888c2-6ca7-40b2-af1e-7694133f9836_1677937238.686007.png)\n\n\n# Approach\n<!-- Describe your approach to solving the p...
1
You are given an integer array `nums` and two integers `minK` and `maxK`. A **fixed-bound subarray** of `nums` is a subarray that satisfies the following conditions: * The **minimum** value in the subarray is equal to `minK`. * The **maximum** value in the subarray is equal to `maxK`. Return _the **number** of f...
null
Video Solution | Easiest Solution using Sliding Window | Python
count-subarrays-with-fixed-bounds
0
1
# Approach\nhttps://youtu.be/vwzal4jbEfw\n\n# Code\n```\nclass Solution:\n def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:\n minFound = False\n maxFound = False\n\n start = 0\n minStart = 0\n maxStart = 0\n count = 0\n\n for i, num in enumerate...
1
You are given an integer array `nums` and two integers `minK` and `maxK`. A **fixed-bound subarray** of `nums` is a subarray that satisfies the following conditions: * The **minimum** value in the subarray is equal to `minK`. * The **maximum** value in the subarray is equal to `maxK`. Return _the **number** of f...
null
[Python] Divide and Expand
count-subarrays-with-fixed-bounds
0
1
**Solution**:\nSince a subarray must contains numbers between minK and maxK, any number outside such range will act as a divider and we can consider subarrays to the left and to the right of it independently.\n\nIterate through all numbers and find the count of valid subarrays ending at each number.\n \nFor a subar...
1
You are given an integer array `nums` and two integers `minK` and `maxK`. A **fixed-bound subarray** of `nums` is a subarray that satisfies the following conditions: * The **minimum** value in the subarray is equal to `minK`. * The **maximum** value in the subarray is equal to `maxK`. Return _the **number** of f...
null
Time 100% Space 90% | Time O(n) Space O(1)
count-subarrays-with-fixed-bounds
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLooking at a few base cases\n1, 5 [1,5] = 1\n1, 5 [2,1,5] = 2\n1, 5 [1,5,1] = 3\n1, 5 [2,1,5,1] = 5\nyou may notice that the count for a single pair of min and max is equal to `amount on left` * `amount on right`.\nFor multiple pairs, the...
1
You are given an integer array `nums` and two integers `minK` and `maxK`. A **fixed-bound subarray** of `nums` is a subarray that satisfies the following conditions: * The **minimum** value in the subarray is equal to `minK`. * The **maximum** value in the subarray is equal to `maxK`. Return _the **number** of f...
null
Python3 Solution using sliding window
count-subarrays-with-fixed-bounds
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires us to find the number of subarrays in an array where the minimum element is at least minK and the maximum element is at most maxK.\nTo solve the problem, I used a sliding window approach.\n# Approach\n<!-- Describe yo...
1
You are given an integer array `nums` and two integers `minK` and `maxK`. A **fixed-bound subarray** of `nums` is a subarray that satisfies the following conditions: * The **minimum** value in the subarray is equal to `minK`. * The **maximum** value in the subarray is equal to `maxK`. Return _the **number** of f...
null
Python short and clean. Functional programming.
count-subarrays-with-fixed-bounds
0
1
# Approach\nTLDR; Same as the [Official Solution](https://leetcode.com/problems/count-subarrays-with-fixed-bounds/editorial/).\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\nwhere, `n is the length of nums`.\n\n# Code\n```python\nclass Solution:\n def countSubarrays(self, nums: list[...
2
You are given an integer array `nums` and two integers `minK` and `maxK`. A **fixed-bound subarray** of `nums` is a subarray that satisfies the following conditions: * The **minimum** value in the subarray is equal to `minK`. * The **maximum** value in the subarray is equal to `maxK`. Return _the **number** of f...
null
[Python3] 1-line
determine-if-two-events-have-conflict
0
1
\n```\nclass Solution:\n def haveConflict(self, event1: List[str], event2: List[str]) -> bool:\n return event1[0] <= event2[0] <= event1[1] or event2[0] <= event1[0] <= event2[1]\n```
8
You are given two arrays of strings that represent two inclusive events that happened **on the same day**, `event1` and `event2`, where: * `event1 = [startTime1, endTime1]` and * `event2 = [startTime2, endTime2]`. Event times are valid 24 hours format in the form of `HH:MM`. A **conflict** happens when two event...
null
Python Elegant & Short
determine-if-two-events-have-conflict
0
1
```\nclass Solution:\n """\n Time: O(1)\n Memory: O(1)\n """\n\n def haveConflict(self, a: List[str], b: List[str]) -> bool:\n a_start, a_end = a\n b_start, b_end = b\n return b_start <= a_start <= b_end or \\\n b_start <= a_end <= b_end or \\\n a_start ...
6
You are given two arrays of strings that represent two inclusive events that happened **on the same day**, `event1` and `event2`, where: * `event1 = [startTime1, endTime1]` and * `event2 = [startTime2, endTime2]`. Event times are valid 24 hours format in the form of `HH:MM`. A **conflict** happens when two event...
null
Python Solution (explanation and super fast)
determine-if-two-events-have-conflict
0
1
![Screenshot 2023-01-01 at 14.35.35.png](https://assets.leetcode.com/users/images/efb09e0d-eb71-410c-8d24-fc43473e4c8d_1672576587.2719238.png)\n\n```\nclass Solution:\n def haveConflict(self, event1: List[str], event2: List[str]) -> bool:\n\n event1Start = event1[0].split(\':\')\n event1End = event1[1]...
4
You are given two arrays of strings that represent two inclusive events that happened **on the same day**, `event1` and `event2`, where: * `event1 = [startTime1, endTime1]` and * `event2 = [startTime2, endTime2]`. Event times are valid 24 hours format in the form of `HH:MM`. A **conflict** happens when two event...
null
[Python3] Straight-Forward, Clean & Concise
determine-if-two-events-have-conflict
0
1
```\nclass Solution:\n def haveConflict(self, event1: List[str], event2: List[str]) -> bool:\n start1 = int(event1[0][:2]) * 60 + int(event1[0][3:])\n end1 = int(event1[1][:2]) * 60 + int(event1[1][3:])\n start2 = int(event2[0][:2]) * 60 + int(event2[0][3:])\n end2 = int(event2[1][:2]) * ...
2
You are given two arrays of strings that represent two inclusive events that happened **on the same day**, `event1` and `event2`, where: * `event1 = [startTime1, endTime1]` and * `event2 = [startTime2, endTime2]`. Event times are valid 24 hours format in the form of `HH:MM`. A **conflict** happens when two event...
null
Simple and Easy 2 lines[Python]
determine-if-two-events-have-conflict
0
1
Convert hours to minutes and compare\n```\nclass Solution:\n def haveConflict(self, event1: List[str], event2: List[str]) -> bool:\n \n arr = [[(int(event1[0][:2])*60)+int(event1[0][3:]) , (int(event1[1][:2])*60)+int(event1[1][3:])] ,\n [(int(event2[0][:2])*60)+int(event2[0][3:]) , (int(e...
2
You are given two arrays of strings that represent two inclusive events that happened **on the same day**, `event1` and `event2`, where: * `event1 = [startTime1, endTime1]` and * `event2 = [startTime2, endTime2]`. Event times are valid 24 hours format in the form of `HH:MM`. A **conflict** happens when two event...
null
[Python3] Brute Force + Early Stopping, Clean & Concise
number-of-subarrays-with-gcd-equal-to-k
0
1
**Implementation**\nWe use a nested for-loop to record the starting index `i` and ending index `j` for the subarray. Each time, when the GCD of subarray is smaller than `k`, we exit the inner for-loop.\n\n**Complexity**\nTime Complexity: `O(N^2logM)`, where `M <= 1e9` (worse case for GCD)\nSpace Complexity: `O(1)`\n \n...
4
Given an integer array `nums` and an integer `k`, return _the number of **subarrays** of_ `nums` _where the greatest common divisor of the subarray's elements is_ `k`. A **subarray** is a contiguous non-empty sequence of elements within an array. The **greatest common divisor of an array** is the largest integer that...
null
Python | brute force
number-of-subarrays-with-gcd-equal-to-k
0
1
# Complexity\n- Time complexity: O(n<sup>2</sup>)\n- Space complexity: O(1)\n\n# Code :\n```\nclass Solution:\n def subarrayGCD(self, nums: List[int], k: int) -> int:\n def gcd(n1, n2):\n if n2==0:\n return n1\n return gcd(n2, n1%n2)\n \n ans = 0\n n =...
1
Given an integer array `nums` and an integer `k`, return _the number of **subarrays** of_ `nums` _where the greatest common divisor of the subarray's elements is_ `k`. A **subarray** is a contiguous non-empty sequence of elements within an array. The **greatest common divisor of an array** is the largest integer that...
null
✔️ [Python3] Straightforward (っ•́。•́)♪♬, Explained
number-of-subarrays-with-gcd-equal-to-k
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAfter spending some time trying to use DP, you realize that it\'s usless here due to complexity reusing subproblems when calculationg GCD.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSimply check all possible s...
0
Given an integer array `nums` and an integer `k`, return _the number of **subarrays** of_ `nums` _where the greatest common divisor of the subarray's elements is_ `k`. A **subarray** is a contiguous non-empty sequence of elements within an array. The **greatest common divisor of an array** is the largest integer that...
null
Binary_Search_Greedy.py
minimum-cost-to-make-array-equal
0
1
# Approach\n<h3>Binary Search</h1>\n\n# Complexity\n- Time complexity:\n $$O(N log N)$$\n\n- Space complexity:\n$$O(1)$$ \n![](https://media.tenor.com/Jl0YrqxnHmAAAAAC/binary-search-sequence-search.gif)\n\n# Code\n```\nclass Solution:\n def minCost(self, nums: List[int], cost: List[int]) -> int:\n ii,j=min(nu...
3
You are given two **0-indexed** arrays `nums` and `cost` consisting each of `n` **positive** integers. You can do the following operation **any** number of times: * Increase or decrease **any** element of the array `nums` by `1`. The cost of doing one operation on the `ith` element is `cost[i]`. Return _the **min...
null
4 lines only... without finding Median✅✅
minimum-cost-to-make-array-equal
0
1
```\nclass Solution:\n def minCost(self, nums: List[int], cost: List[int]) -> int:\n ll = sorted([[nums[i], cost[i]] for i in range(len(cost))])\n c = list(accumulate([ll[i][1] for i in range(len(cost))]))\n nc = list(accumulate([ll[i][0] * ll[i][1] for i in range(len(cost))]))\n return m...
1
You are given two **0-indexed** arrays `nums` and `cost` consisting each of `n` **positive** integers. You can do the following operation **any** number of times: * Increase or decrease **any** element of the array `nums` by `1`. The cost of doing one operation on the `ith` element is `cost[i]`. Return _the **min...
null
Easy Concise Python || Explanation || Without any Median like Hard Concept ✅
minimum-cost-to-make-array-equal
0
1
# Approach\nHere is a simple example of my Approach:\nLet the nums[] be - `[a,b,c]` & cost[] be - `[x,y,z]`\nlet the number which the final nums[] be like - `n`(therefore, the nums[] will be `[n,n,n]`)\n\nThen the `res` will be: `(n-a)x + (n-b)y + (c-n)z`\n> here, assuming `x` is between `b` and `c`\n\nNow, solving thi...
1
You are given two **0-indexed** arrays `nums` and `cost` consisting each of `n` **positive** integers. You can do the following operation **any** number of times: * Increase or decrease **any** element of the array `nums` by `1`. The cost of doing one operation on the `ith` element is `cost[i]`. Return _the **min...
null
Fastest Solution Yet
minimum-cost-to-make-array-equal
0
1
# Intuition\nSince it asked to perform some operation (i.e. increasse/decrease elements by 1), it would be best to use mean of all elements belonging to `cost`. So using the hints we need to perform Iterative traversal and update\n\n# Approach\n1. Sort the elements.\n2. Determine the mean of `cost`.\n3. Create a new va...
1
You are given two **0-indexed** arrays `nums` and `cost` consisting each of `n` **positive** integers. You can do the following operation **any** number of times: * Increase or decrease **any** element of the array `nums` by `1`. The cost of doing one operation on the `ith` element is `cost[i]`. Return _the **min...
null