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
4 lines code in python
make-two-arrays-equal-by-reversing-subarrays
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 of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps. Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_. **Example 1:** **Input:** target = \[1,...
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
Python3 || Easy solution
make-two-arrays-equal-by-reversing-subarrays
0
1
please upvote if you find the solution helpful.\n\n# Code\n```\nclass Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n return sorted(target) == sorted(arr)\n```
1
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps. Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_. **Example 1:** **Input:** target = \[1,...
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
one line code
make-two-arrays-equal-by-reversing-subarrays
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:50%\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:100%\n<!-- Add your space complexity here, e.g. $$O(...
2
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps. Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_. **Example 1:** **Input:** target = \[1,...
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
Simple [Python O(N)] Solution
make-two-arrays-equal-by-reversing-subarrays
0
1
# Intuition JUET\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach brute force\nin this problem first cheak len of target and arr if not equal return False and and if target and arr are equal return True\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time...
1
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps. Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_. **Example 1:** **Input:** target = \[1,...
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
Easy solution using dictionary in python
make-two-arrays-equal-by-reversing-subarrays
0
1
![image](https://assets.leetcode.com/users/images/9eb8d66b-4c0f-453c-964a-772378f17b97_1666411951.4112937.png)\n```\nclass Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n n, m = len(target), len(arr)\n if m > n:\n return False\n t = Counter(target)\n ...
11
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps. Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_. **Example 1:** **Input:** target = \[1,...
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
Python easy solution without using sort, used HashMap, beats 80% in runtime
make-two-arrays-equal-by-reversing-subarrays
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 of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps. Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_. **Example 1:** **Input:** target = \[1,...
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
Python one line | 2 solution
make-two-arrays-equal-by-reversing-subarrays
0
1
**Python :**\n\n**1.** Using collecions.Counter\n**Time complexity :** *O(n)*\n**Space complexity :** *O(n)*\n\n```\ndef canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n\treturn Counter(arr) == Counter(target)\n```\n\n**1.** Sorting the arrays and compare\n**Time complexity :** *O(nlogn)*\n**Space complex...
8
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps. Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_. **Example 1:** **Input:** target = \[1,...
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
Python Counter 1liner
make-two-arrays-equal-by-reversing-subarrays
0
1
```\nclass Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n \n return Counter(arr) == Counter(target)\n```
2
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps. Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_. **Example 1:** **Input:** target = \[1,...
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
Make Two Arrays Equal by Reversing Sub-arrays
make-two-arrays-equal-by-reversing-subarrays
0
1
# python 3 solution :******\n\n```\nclass Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n x = {}\n for i in target:\n if i in x :\n x[i]+=1\n else:\n x[i]=1\n for i in arr:\n if x.get(i):\n ...
1
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps. Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_. **Example 1:** **Input:** target = \[1,...
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
Python 3 fast, no sort, no Counter
make-two-arrays-equal-by-reversing-subarrays
0
1
Runtime: 68 ms, faster than 99.60% of Python3 online submissions for Make Two Arrays Equal by Reversing Sub-arrays.\nMemory Usage: 14.2 MB, less than 10.31% of Python3 online submissions for Make Two Arrays Equal by Reversing Sub-arrays.\n\n```python\nclass Solution:\n def canBeEqual(self, target: List[int], arr: Li...
11
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps. Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_. **Example 1:** **Input:** target = \[1,...
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
✅ Python || 2 Easy || One liner with explanation
check-if-a-string-contains-all-binary-codes-of-size-k
0
1
1. ### **Hashset**\nThe problem description states:\n```\nreturn true if every binary code of length k is a substring of s\n```\n\nSo it\'s not asking us to generate all valid binary code of length `k` from scratch. The main idea here is to check if all the substrings that can be formed from the input `s` is a complete...
26
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f...
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
✅ Python || 2 Easy || One liner with explanation
check-if-a-string-contains-all-binary-codes-of-size-k
0
1
1. ### **Hashset**\nThe problem description states:\n```\nreturn true if every binary code of length k is a substring of s\n```\n\nSo it\'s not asking us to generate all valid binary code of length `k` from scratch. The main idea here is to check if all the substrings that can be formed from the input `s` is a complete...
26
Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`. Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution ...
We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k.
[Python] 4 lines, O(N*k), with explanation
check-if-a-string-contains-all-binary-codes-of-size-k
0
1
This problem statement was incorrect during the contest. We want to find out if **ALL** "binary codes" of length `k` can be found (contiguously) in the string `s`.\n\nSo, for\n`k=1` , we need to find `0` and `1` in `s`. There are 2 binary codes.\n`k=2`, we need to find `00`, `01`, `10`, `11`. There are 4 binary code...
30
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f...
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
[Python] 4 lines, O(N*k), with explanation
check-if-a-string-contains-all-binary-codes-of-size-k
0
1
This problem statement was incorrect during the contest. We want to find out if **ALL** "binary codes" of length `k` can be found (contiguously) in the string `s`.\n\nSo, for\n`k=1` , we need to find `0` and `1` in `s`. There are 2 binary codes.\n`k=2`, we need to find `00`, `01`, `10`, `11`. There are 4 binary code...
30
Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`. Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution ...
We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k.
Python, one-liner
check-if-a-string-contains-all-binary-codes-of-size-k
0
1
```\nclass Solution:\n def hasAllCodes(self, s: str, k: int) -> bool:\n return len(set(s[i:i+k] for i in range(len(s)-k+1))) == 2**k\n```
11
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f...
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
Python, one-liner
check-if-a-string-contains-all-binary-codes-of-size-k
0
1
```\nclass Solution:\n def hasAllCodes(self, s: str, k: int) -> bool:\n return len(set(s[i:i+k] for i in range(len(s)-k+1))) == 2**k\n```
11
Given a **directed acyclic graph**, with `n` vertices numbered from `0` to `n-1`, and an array `edges` where `edges[i] = [fromi, toi]` represents a directed edge from node `fromi` to node `toi`. Find _the smallest set of vertices from which all nodes in the graph are reachable_. It's guaranteed that a unique solution ...
We need only to check all sub-strings of length k. The number of distinct sub-strings should be exactly 2^k.
SIMPLE PYTHON SOLUTION
course-schedule-iv
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTOPOLOGICAL SORT\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:$$O(V*ElogE)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(V*E)$$\n<!-- Add yo...
1
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take course `bi`. * For example, the pair `[0, 1]` indicates that you have to ...
null
SIMPLE PYTHON SOLUTION
course-schedule-iv
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTOPOLOGICAL SORT\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:$$O(V*ElogE)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(V*E)$$\n<!-- Add yo...
1
You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function: You want to use the modify function to covert `arr` to `nums` using the minimum number of calls. Return _the minimum number of function calls t...
Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array.
Python-Easy to understand Topological sort , beats 100%
course-schedule-iv
0
1
# If you find it useful, please upvote it so that others can find it easily.\n# Complexity\n- Time complexity:\no(n(p+n)q)\n# please upvote if found helpful\n# Code\n```\nclass Solution(object):\n def checkIfPrerequisite(self, numCourses, prerequisites, queries):\n adj={i:[] for i in range(numCourses)}\n\n ...
6
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take course `bi`. * For example, the pair `[0, 1]` indicates that you have to ...
null
Python-Easy to understand Topological sort , beats 100%
course-schedule-iv
0
1
# If you find it useful, please upvote it so that others can find it easily.\n# Complexity\n- Time complexity:\no(n(p+n)q)\n# please upvote if found helpful\n# Code\n```\nclass Solution(object):\n def checkIfPrerequisite(self, numCourses, prerequisites, queries):\n adj={i:[] for i in range(numCourses)}\n\n ...
6
You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function: You want to use the modify function to covert `arr` to `nums` using the minimum number of calls. Return _the minimum number of function calls t...
Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array.
python3 recursion + memoization
course-schedule-iv
0
1
\n\n# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n\n @cache\n def check(n,target):\n nonlocal d\n if n == target:\n return ...
1
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take course `bi`. * For example, the pair `[0, 1]` indicates that you have to ...
null
python3 recursion + memoization
course-schedule-iv
0
1
\n\n# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n\n @cache\n def check(n,target):\n nonlocal d\n if n == target:\n return ...
1
You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function: You want to use the modify function to covert `arr` to `nums` using the minimum number of calls. Return _the minimum number of function calls t...
Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array.
[python3][Topological Sort][BFS] Clear solution with comments
course-schedule-iv
0
1
Summary: the idea is to use topological sort to create a prerequisite lookup dictionary. \n\nSince this method is query-intensive, so we need to have O(1) time for query. In this case, we need to create a dictionary with each course as the key and the value is a set including all the prerequisites of this course. This ...
13
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take course `bi`. * For example, the pair `[0, 1]` indicates that you have to ...
null
[python3][Topological Sort][BFS] Clear solution with comments
course-schedule-iv
0
1
Summary: the idea is to use topological sort to create a prerequisite lookup dictionary. \n\nSince this method is query-intensive, so we need to have O(1) time for query. In this case, we need to create a dictionary with each course as the key and the value is a set including all the prerequisites of this course. This ...
13
You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function: You want to use the modify function to covert `arr` to `nums` using the minimum number of calls. Return _the minimum number of function calls t...
Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array.
( ͡° ͜ʖ ͡°)👉|| Beats 97.99%|| JAVA|| PYTHON||EASY SOLUTION💯☑️
course-schedule-iv
1
1
# If you find it useful, please upvote so that others can find it easily.\n# Code\n```Java []\nclass Solution {\n public void fillGraph(boolean[][] graph, int i, boolean[] visited){\n if (visited[i])\n return;\n visited[i] = true;\n for (int j=0;j<graph[i].length;j++){\n if...
2
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take course `bi`. * For example, the pair `[0, 1]` indicates that you have to ...
null
( ͡° ͜ʖ ͡°)👉|| Beats 97.99%|| JAVA|| PYTHON||EASY SOLUTION💯☑️
course-schedule-iv
1
1
# If you find it useful, please upvote so that others can find it easily.\n# Code\n```Java []\nclass Solution {\n public void fillGraph(boolean[][] graph, int i, boolean[] visited){\n if (visited[i])\n return;\n visited[i] = true;\n for (int j=0;j<graph[i].length;j++){\n if...
2
You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function: You want to use the modify function to covert `arr` to `nums` using the minimum number of calls. Return _the minimum number of function calls t...
Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array.
Simple Solution DFS ( finding Indirectly connected edges ) , in Python
course-schedule-iv
0
1
# Code\n```\nclass Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n\n graph = {}\n for i in range(numCourses): graph[i] = []\n\n for u , v in prerequisites: \n graph[u] += [v]\n\n d = {} ...
1
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take course `bi`. * For example, the pair `[0, 1]` indicates that you have to ...
null
Simple Solution DFS ( finding Indirectly connected edges ) , in Python
course-schedule-iv
0
1
# Code\n```\nclass Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n\n graph = {}\n for i in range(numCourses): graph[i] = []\n\n for u , v in prerequisites: \n graph[u] += [v]\n\n d = {} ...
1
You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function: You want to use the modify function to covert `arr` to `nums` using the minimum number of calls. Return _the minimum number of function calls t...
Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array.
[Python] DP + Reachability Test (Since its a DAG)
course-schedule-iv
0
1
```\nclass Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n adjList = {}\n for i in range(numCourses):\n adjList[i] = []\n for i in prerequisites:\n adjList[i[0]].append(i[1])\n \n ...
0
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `ai` first if you want to take course `bi`. * For example, the pair `[0, 1]` indicates that you have to ...
null
[Python] DP + Reachability Test (Since its a DAG)
course-schedule-iv
0
1
```\nclass Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n adjList = {}\n for i in range(numCourses):\n adjList[i] = []\n for i in prerequisites:\n adjList[i[0]].append(i[1])\n \n ...
0
You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function: You want to use the modify function to covert `arr` to `nums` using the minimum number of calls. Return _the minimum number of function calls t...
Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array.
Python 2 Solutions Very Easy to Understand
cherry-pickup-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nDynamic Programming\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 h...
1
You are given a `rows x cols` matrix `grid` representing a field of cherries where `grid[i][j]` represents the number of cherries that you can collect from the `(i, j)` cell. You have two robots that can collect cherries for you: * **Robot #1** is located at the **top-left corner** `(0, 0)`, and * **Robot #2** is...
Sort the matrix row indexes by the number of soldiers and then row indexes.
Python 2 Solutions Very Easy to Understand
cherry-pickup-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nDynamic Programming\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 h...
1
Given a 2D array of characters `grid` of size `m x n`, you need to find if there exists any cycle consisting of the **same value** in `grid`. A cycle is a path of **length 4 or more** in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the f...
Use dynammic programming, define DP[i][j][k]: The maximum cherries that both robots can take starting on the ith row, and column j and k of Robot 1 and 2 respectively.
❤ [Python3] DYNAMIC PROGRAMMING (*´∇`)ノ, Explained
cherry-pickup-ii
0
1
We approach this problem using DP. For a table we define `dp[row][col_r1][col_r2]`: the maximum reward both robots can get starting at the row `row` and columns `col_r1` and `col_r2` for the first and second robot respectively. For example: `dp[1][3][7] = 11` means that both robots can pickup maximum 11 cherries if th...
15
You are given a `rows x cols` matrix `grid` representing a field of cherries where `grid[i][j]` represents the number of cherries that you can collect from the `(i, j)` cell. You have two robots that can collect cherries for you: * **Robot #1** is located at the **top-left corner** `(0, 0)`, and * **Robot #2** is...
Sort the matrix row indexes by the number of soldiers and then row indexes.
❤ [Python3] DYNAMIC PROGRAMMING (*´∇`)ノ, Explained
cherry-pickup-ii
0
1
We approach this problem using DP. For a table we define `dp[row][col_r1][col_r2]`: the maximum reward both robots can get starting at the row `row` and columns `col_r1` and `col_r2` for the first and second robot respectively. For example: `dp[1][3][7] = 11` means that both robots can pickup maximum 11 cherries if th...
15
Given a 2D array of characters `grid` of size `m x n`, you need to find if there exists any cycle consisting of the **same value** in `grid`. A cycle is a path of **length 4 or more** in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the f...
Use dynammic programming, define DP[i][j][k]: The maximum cherries that both robots can take starting on the ith row, and column j and k of Robot 1 and 2 respectively.
【Video】Give me 5 minutes - 2 solutions - How we think about a solution
maximum-product-of-two-elements-in-an-array
1
1
# Intuition\nKeep the largest number so far\n\n---\n\n# Solution Video\n\nhttps://youtu.be/JV5Kuinx-m0\n\n\u25A0 Timeline of the video\n\n`0:05` Explain algorithm of Solution 1\n`3:18` Coding of solution 1\n`4:18` Time Complexity and Space Complexity of solution 1\n`4:29` Step by step algorithm of solution 1\n`4:36` Ex...
27
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`. **Example 1:** **Input:** nums = \[3,4,5,2\] **Output:** 12 **Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum v...
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
【Video】Give me 5 minutes - 2 solutions - How we think about a solution
maximum-product-of-two-elements-in-an-array
1
1
# Intuition\nKeep the largest number so far\n\n---\n\n# Solution Video\n\nhttps://youtu.be/JV5Kuinx-m0\n\n\u25A0 Timeline of the video\n\n`0:05` Explain algorithm of Solution 1\n`3:18` Coding of solution 1\n`4:18` Time Complexity and Space Complexity of solution 1\n`4:29` Step by step algorithm of solution 1\n`4:36` Ex...
27
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
✅✅|| EASY PEASY || C#, Java, Python || 🔥🔥🔥
maximum-product-of-two-elements-in-an-array
1
1
# Intuition\nThe problem involves finding the maximum product of two elements in an array. The provided code suggests an approach of iteratively updating the two largest elements in the array as we traverse through it.\n\n# Approach\n1. Initialize two variables, `max1` and `max2`, to store the two largest elements in t...
11
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`. **Example 1:** **Input:** nums = \[3,4,5,2\] **Output:** 12 **Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum v...
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
✅✅|| EASY PEASY || C#, Java, Python || 🔥🔥🔥
maximum-product-of-two-elements-in-an-array
1
1
# Intuition\nThe problem involves finding the maximum product of two elements in an array. The provided code suggests an approach of iteratively updating the two largest elements in the array as we traverse through it.\n\n# Approach\n1. Initialize two variables, `max1` and `max2`, to store the two largest elements in t...
11
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
2 C++ 1 pass, priority_queue O(1) vs 3 Python 1-line codes|| 0ms beats 100%
maximum-product-of-two-elements-in-an-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIterate the `nums` to find the max & 2nd max.\n\n2nd O(1) C++ solution uses priority_queue of size at most 3 which is also fast & beats 100%.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nPython codes are provided ...
8
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`. **Example 1:** **Input:** nums = \[3,4,5,2\] **Output:** 12 **Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum v...
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
2 C++ 1 pass, priority_queue O(1) vs 3 Python 1-line codes|| 0ms beats 100%
maximum-product-of-two-elements-in-an-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIterate the `nums` to find the max & 2nd max.\n\n2nd O(1) C++ solution uses priority_queue of size at most 3 which is also fast & beats 100%.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nPython codes are provided ...
8
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
✅☑[C++/Java/Python/JavaScript] || 3 Approaches || Beats 100% || EXPLAINED🔥
maximum-product-of-two-elements-in-an-array
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Brute Force)***\n1. The function iterates through the elements in the `nums` array using two nested loops (`i` and `j`) to consider all possible pairs of elements.\n1. For each pair of elements (`nums[i], nums[...
21
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`. **Example 1:** **Input:** nums = \[3,4,5,2\] **Output:** 12 **Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum v...
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
✅☑[C++/Java/Python/JavaScript] || 3 Approaches || Beats 100% || EXPLAINED🔥
maximum-product-of-two-elements-in-an-array
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Brute Force)***\n1. The function iterates through the elements in the `nums` array using two nested loops (`i` and `j`) to consider all possible pairs of elements.\n1. For each pair of elements (`nums[i], nums[...
21
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
🚀🚀 Beats 100% | 0ms 🔥🔥
maximum-product-of-two-elements-in-an-array
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $...
3
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`. **Example 1:** **Input:** nums = \[3,4,5,2\] **Output:** 12 **Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum v...
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
🚀🚀 Beats 100% | 0ms 🔥🔥
maximum-product-of-two-elements-in-an-array
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $...
3
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
Python3 Solution
maximum-product-of-two-elements-in-an-array
0
1
\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums.sort()\n return (nums[-1]-1)*(nums[-2]-1)\n```
3
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`. **Example 1:** **Input:** nums = \[3,4,5,2\] **Output:** 12 **Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum v...
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
Python3 Solution
maximum-product-of-two-elements-in-an-array
0
1
\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n nums.sort()\n return (nums[-1]-1)*(nums[-2]-1)\n```
3
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
Easy and simple soultion using python and java with explaination
maximum-product-of-two-elements-in-an-array
1
1
# Intuition\n\n\nThe problem involves finding the maximum product of two elements in an array. A potential approach is to sort the array and then multiply the two largest elements, which are the last two elements in the sorted array.\n\n# Approach\n\n\n1. Sort the array in ascending order.\n2. Subract last two elements...
2
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`. **Example 1:** **Input:** nums = \[3,4,5,2\] **Output:** 12 **Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum v...
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
Easy and simple soultion using python and java with explaination
maximum-product-of-two-elements-in-an-array
1
1
# Intuition\n\n\nThe problem involves finding the maximum product of two elements in an array. A potential approach is to sort the array and then multiply the two largest elements, which are the last two elements in the sorted array.\n\n# Approach\n\n\n1. Sort the array in ascending order.\n2. Subract last two elements...
2
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
Try with Heap | Simple Solution
maximum-product-of-two-elements-in-an-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`. **Example 1:** **Input:** nums = \[3,4,5,2\] **Output:** 12 **Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum v...
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
Try with Heap | Simple Solution
maximum-product-of-two-elements-in-an-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
O(n) Time complexity solution! (no sorting required)
maximum-product-of-two-elements-in-an-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* creating a negated list bcuz python by default offers min heap. so to get max element out of min heap we are multiplying the elements by -1.\n* pop two highest eleme...
2
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`. **Example 1:** **Input:** nums = \[3,4,5,2\] **Output:** 12 **Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum v...
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
O(n) Time complexity solution! (no sorting required)
maximum-product-of-two-elements-in-an-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* creating a negated list bcuz python by default offers min heap. so to get max element out of min heap we are multiplying the elements by -1.\n* pop two highest eleme...
2
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
✅✅ One Liner ✅✅ beats 96.2% 🔥🥶
maximum-product-of-two-elements-in-an-array
0
1
![image.png](https://assets.leetcode.com/users/images/a2939d74-d290-4f94-b9a5-2fd23d38ab21_1702375144.5702415.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGo through list to find two largest values, then compute solution\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add...
1
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`. **Example 1:** **Input:** nums = \[3,4,5,2\] **Output:** 12 **Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum v...
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
✅✅ One Liner ✅✅ beats 96.2% 🔥🥶
maximum-product-of-two-elements-in-an-array
0
1
![image.png](https://assets.leetcode.com/users/images/a2939d74-d290-4f94-b9a5-2fd23d38ab21_1702375144.5702415.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGo through list to find two largest values, then compute solution\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add...
1
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
Sidha-Sadha Solution🤞🤞🤞🤞
maximum-product-of-two-elements-in-an-array
0
1
# Intuition\nFind 1st maximum and 2nd maximum .\nsubstract one from both and return their product\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\ninitialize max1 and max2 form first two element.\nRun for loop from 2 to length of array.\nUpdate max1 and max2 in each iteration if neede...
1
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`. **Example 1:** **Input:** nums = \[3,4,5,2\] **Output:** 12 **Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum v...
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
Sidha-Sadha Solution🤞🤞🤞🤞
maximum-product-of-two-elements-in-an-array
0
1
# Intuition\nFind 1st maximum and 2nd maximum .\nsubstract one from both and return their product\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\ninitialize max1 and max2 form first two element.\nRun for loop from 2 to length of array.\nUpdate max1 and max2 in each iteration if neede...
1
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
✅ 2 line solution || ✅ simple || ✅ python
maximum-product-of-two-elements-in-an-array
0
1
# Intuition\nThe problem asks for the maximum product of two distinct elements in the given list. Sorting the list in ascending order allows us to access the two largest elements at the end of the sorted list.\n\n\n# Approach\nThe approach involves sorting the input list in ascending order. After sorting, the two large...
8
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`. **Example 1:** **Input:** nums = \[3,4,5,2\] **Output:** 12 **Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum v...
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
✅ 2 line solution || ✅ simple || ✅ python
maximum-product-of-two-elements-in-an-array
0
1
# Intuition\nThe problem asks for the maximum product of two distinct elements in the given list. Sorting the list in ascending order allows us to access the two largest elements at the end of the sorted list.\n\n\n# Approach\nThe approach involves sorting the input list in ascending order. After sorting, the two large...
8
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
Easiest Solution || Python using max
maximum-product-of-two-elements-in-an-array
0
1
# Intuition\nWe know that the answer will be the product of maximum and 2nd maximum.\nThus we find the maximum and store it then remove it to find the 2nd maximum.\n\n# Code\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n m1=max(nums)\n nums.remove(m1)\n m2=max(nums)\n ...
1
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`. **Example 1:** **Input:** nums = \[3,4,5,2\] **Output:** 12 **Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum v...
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
Easiest Solution || Python using max
maximum-product-of-two-elements-in-an-array
0
1
# Intuition\nWe know that the answer will be the product of maximum and 2nd maximum.\nThus we find the maximum and store it then remove it to find the 2nd maximum.\n\n# Code\n```\nclass Solution:\n def maxProduct(self, nums: List[int]) -> int:\n m1=max(nums)\n nums.remove(m1)\n m2=max(nums)\n ...
1
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
Simple solution with Sorting in Python3
maximum-product-of-two-elements-in-an-array
0
1
# Intuition\nHere we have an array of integers `nums`.\nOur goal is to extract **maximum product** between two integers such as `(nums[i]-1)*(nums[j]-1)`\n\n# Approach \nSimply sort an array and take **two** largest integers.\n\n# Complexity\n- Time complexity: **O(N log N)**\n\n- Space complexity: **O(1)**\n\n# Code\n...
1
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`. **Example 1:** **Input:** nums = \[3,4,5,2\] **Output:** 12 **Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum v...
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
Simple solution with Sorting in Python3
maximum-product-of-two-elements-in-an-array
0
1
# Intuition\nHere we have an array of integers `nums`.\nOur goal is to extract **maximum product** between two integers such as `(nums[i]-1)*(nums[j]-1)`\n\n# Approach \nSimply sort an array and take **two** largest integers.\n\n# Complexity\n- Time complexity: **O(N log N)**\n\n- Space complexity: **O(1)**\n\n# Code\n...
1
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are **non-decreasing**. Return _the length of the shortest subarray to remove_. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,2,3,10,4,2,3,5\] **Output:*...
Use brute force: two loops to select i and j, then select the maximum value of (nums[i]-1)*(nums[j]-1).
Python easy solution
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
0
1
```\nclass Solution:\n def maxArea(self, h: int, w: int, hc: List[int], vc: List[int]) -> int:\n \n hc.sort()\n vc.sort()\n \n maxh = hc[0]\n maxv = vc[0]\n \n for i in range(1, len(hc)):\n maxh = max(maxh, hc[i] - hc[i-1])\n maxh = max(maxh, ...
3
You are given a rectangular cake of size `h x w` and two arrays of integers `horizontalCuts` and `verticalCuts` where: * `horizontalCuts[i]` is the distance from the top of the rectangular cake to the `ith` horizontal cut and similarly, and * `verticalCuts[j]` is the distance from the left of the rectangular cake ...
If we know the sum of a subtree, the answer is max( (total_sum - subtree_sum) * subtree_sum) in each node.
Python easy solution
maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
0
1
```\nclass Solution:\n def maxArea(self, h: int, w: int, hc: List[int], vc: List[int]) -> int:\n \n hc.sort()\n vc.sort()\n \n maxh = hc[0]\n maxv = vc[0]\n \n for i in range(1, len(hc)):\n maxh = max(maxh, hc[i] - hc[i-1])\n maxh = max(maxh, ...
3
You are given an array of **distinct** positive integers locations where `locations[i]` represents the position of city `i`. You are also given integers `start`, `finish` and `fuel` representing the starting city, ending city, and the initial amount of fuel you have, respectively. At each step, if you are at city `i`,...
Sort the arrays, then compute the maximum difference between two consecutive elements for horizontal cuts and vertical cuts. The answer is the product of these maximum values in horizontal cuts and vertical cuts.
Python O(E) bfs solution
reorder-routes-to-make-all-paths-lead-to-the-city-zero
0
1
\n\n\n```\n def minReorder(self, n: int, connections: List[List[int]]) -> int:\n graph = [ [] for i in range(0,n)]\n\n for item in connections:\n graph[item[0]].append( [item[1],0] )\n graph[item[1]].append( [item[0],1] )\n\n dq = deque()\n dq.append(0)\n visi...
2
There are `n` cities numbered from `0` to `n - 1` and `n - 1` roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by `connections` wh...
Use dynamic programming. dp[i] is max jumps you can do starting from index i. Answer is max(dp[i]). dp[i] = 1 + max (dp[j]) where j is all indices you can reach from i.
Python O(E) bfs solution
reorder-routes-to-make-all-paths-lead-to-the-city-zero
0
1
\n\n\n```\n def minReorder(self, n: int, connections: List[List[int]]) -> int:\n graph = [ [] for i in range(0,n)]\n\n for item in connections:\n graph[item[0]].append( [item[1],0] )\n graph[item[1]].append( [item[0],1] )\n\n dq = deque()\n dq.append(0)\n visi...
2
Given a string `s` containing only lowercase English letters and the `'?'` character, convert **all** the `'?'` characters into lowercase letters such that the final string does not contain any **consecutive repeating** characters. You **cannot** modify the non `'?'` characters. It is **guaranteed** that there are no ...
Treat the graph as undirected. Start a dfs from the root, if you come across an edge in the forward direction, you need to reverse the edge.
Python short and clean. DFS. Functional programming.
reorder-routes-to-make-all-paths-lead-to-the-city-zero
0
1
# Approach\nTL;DR, Same as [Official solution](https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/editorial/).\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```python\nclass Solution:\n def minReorder(self, n: int, connections: list[list[int...
2
There are `n` cities numbered from `0` to `n - 1` and `n - 1` roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by `connections` wh...
Use dynamic programming. dp[i] is max jumps you can do starting from index i. Answer is max(dp[i]). dp[i] = 1 + max (dp[j]) where j is all indices you can reach from i.
Python short and clean. DFS. Functional programming.
reorder-routes-to-make-all-paths-lead-to-the-city-zero
0
1
# Approach\nTL;DR, Same as [Official solution](https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/editorial/).\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```python\nclass Solution:\n def minReorder(self, n: int, connections: list[list[int...
2
Given a string `s` containing only lowercase English letters and the `'?'` character, convert **all** the `'?'` characters into lowercase letters such that the final string does not contain any **consecutive repeating** characters. You **cannot** modify the non `'?'` characters. It is **guaranteed** that there are no ...
Treat the graph as undirected. Start a dfs from the root, if you come across an edge in the forward direction, you need to reverse the edge.
Simple python solution using BFS traversal
reorder-routes-to-make-all-paths-lead-to-the-city-zero
0
1
```\nclass Solution:\n def minReorder(self, n: int, connections: List[List[int]]) -> int:\n visited=[0]*n\n indegree=[[] for _ in range(n)]\n outdegree=[[] for _ in range(n)]\n for frm,to in connections:\n indegree[to].append(frm)\n outdegree[frm].append(to)\n ...
3
There are `n` cities numbered from `0` to `n - 1` and `n - 1` roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by `connections` wh...
Use dynamic programming. dp[i] is max jumps you can do starting from index i. Answer is max(dp[i]). dp[i] = 1 + max (dp[j]) where j is all indices you can reach from i.
Simple python solution using BFS traversal
reorder-routes-to-make-all-paths-lead-to-the-city-zero
0
1
```\nclass Solution:\n def minReorder(self, n: int, connections: List[List[int]]) -> int:\n visited=[0]*n\n indegree=[[] for _ in range(n)]\n outdegree=[[] for _ in range(n)]\n for frm,to in connections:\n indegree[to].append(frm)\n outdegree[frm].append(to)\n ...
3
Given a string `s` containing only lowercase English letters and the `'?'` character, convert **all** the `'?'` characters into lowercase letters such that the final string does not contain any **consecutive repeating** characters. You **cannot** modify the non `'?'` characters. It is **guaranteed** that there are no ...
Treat the graph as undirected. Start a dfs from the root, if you come across an edge in the forward direction, you need to reverse the edge.
Backtracking py3
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
0
1
```\nclass Solution:\n def getProbability(self, balls: List[int]) -> float:\n n = sum(balls)\n self.boxa = [0 for a in balls]\n self.boxb = [0 for a in balls]\n self.total = 0\n self.valid = 0\n m = len(balls)\n def dfs(i): # processing the ith color \n if ...
0
Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`. All the balls will be **shuffled uniformly at random**, then we will distribute the first `n` balls to the first box and the remaining `n` balls to the other box (Please...
null
Backtracking py3
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
0
1
```\nclass Solution:\n def getProbability(self, balls: List[int]) -> float:\n n = sum(balls)\n self.boxa = [0 for a in balls]\n self.boxb = [0 for a in balls]\n self.total = 0\n self.valid = 0\n m = len(balls)\n def dfs(i): # processing the ith color \n if ...
0
Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules: * Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k < nums2.length`. * Type 2: Triplet (i, j, k) if `nums2[i]2 == nums1[j...
Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of ...
Python | complicated Solution
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`. All the balls will be **shuffled uniformly at random**, then we will distribute the first `n` balls to the first box and the remaining `n` balls to the other box (Please...
null
Python | complicated Solution
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules: * Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k < nums2.length`. * Type 2: Triplet (i, j, k) if `nums2[i]2 == nums1[j...
Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of ...
Object Oriented for Memory Optimization
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can consider a dynamic programming approach concerning a valid combination. \nA valid combination is one in which all colors have been used, there are no left overs of a color, and both buckets have an equal number of distinct colors. ...
0
Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`. All the balls will be **shuffled uniformly at random**, then we will distribute the first `n` balls to the first box and the remaining `n` balls to the other box (Please...
null
Object Oriented for Memory Optimization
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can consider a dynamic programming approach concerning a valid combination. \nA valid combination is one in which all colors have been used, there are no left overs of a color, and both buckets have an equal number of distinct colors. ...
0
Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules: * Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k < nums2.length`. * Type 2: Triplet (i, j, k) if `nums2[i]2 == nums1[j...
Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of ...
Python3 using permutations and factorials (It is a math question)
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`. All the balls will be **shuffled uniformly at random**, then we will distribute the first `n` balls to the first box and the remaining `n` balls to the other box (Please...
null
Python3 using permutations and factorials (It is a math question)
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules: * Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k < nums2.length`. * Type 2: Triplet (i, j, k) if `nums2[i]2 == nums1[j...
Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of ...
python solution
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
0
1
Runtime 40ms. Beats 99.21%\n# Code\n```\nclass Solution:\n\n def C(self, n, r) -> int:\n return self.l[int(n)] / self.l[int(r)] / self.l[int(n - r)]\n \'\'\'\n params:\n idx -> what color to consider now\n first -> how many balls are filled to box 1\n second -> how many balls are fi...
0
Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`. All the balls will be **shuffled uniformly at random**, then we will distribute the first `n` balls to the first box and the remaining `n` balls to the other box (Please...
null
python solution
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
0
1
Runtime 40ms. Beats 99.21%\n# Code\n```\nclass Solution:\n\n def C(self, n, r) -> int:\n return self.l[int(n)] / self.l[int(r)] / self.l[int(n - r)]\n \'\'\'\n params:\n idx -> what color to consider now\n first -> how many balls are filled to box 1\n second -> how many balls are fi...
0
Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules: * Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k < nums2.length`. * Type 2: Triplet (i, j, k) if `nums2[i]2 == nums1[j...
Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of ...
Python Solution with Explanation
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
1
1
\tclass Solution:\n\t\tdef getProbability(self, balls: List[int]) -> float:\n\t\t\tdef solve(idx,num,k1,k2,p):\n\t\t\t\t#num is representing total number of balls in box1\n\t\t\t\t#k1 is representing the distinct balls in box1\n\t\t\t\t#k2 is representing the distinct balls in box2\n\t\t\t\t#p is representing the ways ...
0
Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`. All the balls will be **shuffled uniformly at random**, then we will distribute the first `n` balls to the first box and the remaining `n` balls to the other box (Please...
null
Python Solution with Explanation
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
1
1
\tclass Solution:\n\t\tdef getProbability(self, balls: List[int]) -> float:\n\t\t\tdef solve(idx,num,k1,k2,p):\n\t\t\t\t#num is representing total number of balls in box1\n\t\t\t\t#k1 is representing the distinct balls in box1\n\t\t\t\t#k2 is representing the distinct balls in box2\n\t\t\t\t#p is representing the ways ...
0
Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules: * Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k < nums2.length`. * Type 2: Triplet (i, j, k) if `nums2[i]2 == nums1[j...
Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of ...
[Python3] 52ms Solution Explained, beats 100%
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
0
1
**Big Idea: Dynamic Programming**\n\nFirst of all, let\'s propose this combination of values as a DP state:\n\n**(i, disl, disr, numl, numr)**\n\nwhere:\n**i** indicates we use up to the ith type of ball\n**disl** and **disr** are the **number of distinct types** of balls in the left and right bin\n**numl** and **numr*...
4
Given `2n` balls of `k` distinct colors. You will be given an integer array `balls` of size `k` where `balls[i]` is the number of balls of color `i`. All the balls will be **shuffled uniformly at random**, then we will distribute the first `n` balls to the first box and the remaining `n` balls to the other box (Please...
null
[Python3] 52ms Solution Explained, beats 100%
probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
0
1
**Big Idea: Dynamic Programming**\n\nFirst of all, let\'s propose this combination of values as a DP state:\n\n**(i, disl, disr, numl, numr)**\n\nwhere:\n**i** indicates we use up to the ith type of ball\n**disl** and **disr** are the **number of distinct types** of balls in the left and right bin\n**numl** and **numr*...
4
Given two arrays of integers `nums1` and `nums2`, return the number of triplets formed (type 1 and type 2) under the following rules: * Type 1: Triplet (i, j, k) if `nums1[i]2 == nums2[j] * nums2[k]` where `0 <= i < nums1.length` and `0 <= j < k < nums2.length`. * Type 2: Triplet (i, j, k) if `nums2[i]2 == nums1[j...
Check how many ways you can distribute the balls between the boxes. Consider that one way you will use (x1, x2, x3, ..., xk) where xi is the number of balls from colour i. The probability of achieving this way randomly is ( (ball1 C x1) * (ball2 C x2) * (ball3 C x3) * ... * (ballk C xk)) / (2n C n). The probability of ...
Solutions in C++ and Python👊Learn and Master Arrays in Programming(^_+)
shuffle-the-array
0
1
# Solution in C++\n```\nclass Solution {\npublic:\n vector<int> shuffle(vector<int>& nums, int n) {\n vector<int>result;\n for (int i = 0; i < nums.size() / 2; i++){\n result.push_back(nums.at(i));\n result.push_back(nums.at(i+n));\n }\n return result;\n }\n};\n``...
2
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. _Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`. **Example 1:** **Input:** nums = \[2,5,1,3,4,7\], n = 3 **Output:** \[2,3,5,4,1,7\] **Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer ...
null
Beats 86.91% | Shuffle the array
shuffle-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
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. _Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`. **Example 1:** **Input:** nums = \[2,5,1,3,4,7\], n = 3 **Output:** \[2,3,5,4,1,7\] **Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer ...
null
Simple python3 solution, have a nice day.
shuffle-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$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def shuffle(self, nums: List[int], n: int) -> List[i...
1
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. _Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`. **Example 1:** **Input:** nums = \[2,5,1,3,4,7\], n = 3 **Output:** \[2,3,5,4,1,7\] **Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer ...
null
Rust and Python O(n) space. 100% faster in Rust.
shuffle-the-array
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n\nSimple map/List comprehension iteration over the given vetor/List.\nIt\'s really efficient, it seems for Rust.\n\n![Screenshot from 2023-02-06 12-50-26.png](https://assets.leetcode.com/users/images/dc47f26f-e037-4158-af31-c792d0990bfb_1675668097.692...
2
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. _Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`. **Example 1:** **Input:** nums = \[2,5,1,3,4,7\], n = 3 **Output:** \[2,3,5,4,1,7\] **Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer ...
null
python3 two pointer
the-k-strongest-values-in-an-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n O(NlogN)\n\n- Space complexity:\n O(N)\n# Code\n```\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> ...
1
Given an array of integers `arr` and an integer `k`. A value `arr[i]` is said to be stronger than a value `arr[j]` if `|arr[i] - m| > |arr[j] - m|` where `m` is the **median** of the array. If `|arr[i] - m| == |arr[j] - m|`, then `arr[i]` is said to be stronger than `arr[j]` if `arr[i] > arr[j]`. Return _a list of ...
Students in row i only can see exams in row i+1. Use Dynamic programming to compute the result given a (current row, bitmask people seated in previous row).
[Python3] straightforward 2 lines with custom sort
the-k-strongest-values-in-an-array
0
1
1. get median by sorting and getting the `(n-1)/2` th element\n2. use lambda to do custom sort. since we need maximum, take negative of difference. if difference is equal, we just get the larger value element\n\n```\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n m = sorted(a...
16
Given an array of integers `arr` and an integer `k`. A value `arr[i]` is said to be stronger than a value `arr[j]` if `|arr[i] - m| > |arr[j] - m|` where `m` is the **median** of the array. If `|arr[i] - m| == |arr[j] - m|`, then `arr[i]` is said to be stronger than `arr[j]` if `arr[i] > arr[j]`. Return _a list of ...
Students in row i only can see exams in row i+1. Use Dynamic programming to compute the result given a (current row, bitmask people seated in previous row).
Python solution (2 lines) 100% faster runtime
the-k-strongest-values-in-an-array
0
1
\n```\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n med = sorted(arr[(len(arr)-1)//2])\n \xA0 \xA0 \xA0 \xA0return sorted(array, key=lambda x:(abs(x-med),x))[-k:]\n```
8
Given an array of integers `arr` and an integer `k`. A value `arr[i]` is said to be stronger than a value `arr[j]` if `|arr[i] - m| > |arr[j] - m|` where `m` is the **median** of the array. If `|arr[i] - m| == |arr[j] - m|`, then `arr[i]` is said to be stronger than `arr[j]` if `arr[i] > arr[j]`. Return _a list of ...
Students in row i only can see exams in row i+1. Use Dynamic programming to compute the result given a (current row, bitmask people seated in previous row).
Easy python solution🐍🔥
design-browser-history
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(1), O(1), O(n), O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1), O(1), O(1), O(1)\n<!-- Add ...
1
You have a **browser** of one tab where you start on the `homepage` and you can visit another `url`, get back in the history number of `steps` or move forward in the history number of `steps`. Implement the `BrowserHistory` class: * `BrowserHistory(string homepage)` Initializes the object with the `homepage` of the...
Count the frequency of each character. Loop over all character from 'a' to 'z' and append the character if it exists and decrease frequency by 1. Do the same from 'z' to 'a'. Keep repeating until the frequency of all characters is zero.
Easy python solution🐍🔥
design-browser-history
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(1), O(1), O(n), O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1), O(1), O(1), O(1)\n<!-- Add ...
1
Given an `m x n` binary matrix `mat`, return _the number of special positions in_ `mat`_._ A position `(i, j)` is called **special** if `mat[i][j] == 1` and all other elements in row `i` and column `j` are `0` (rows and columns are **0-indexed**). **Example 1:** **Input:** mat = \[\[1,0,0\],\[0,0,1\],\[1,0,0\]\] **O...
Use two stack one for back history and one for forward history and simulate the functions. Can you do faster by using different data structure ?
Dynamic Array | Explained | O(1) each operation | C++ | Python
design-browser-history
0
1
\n<iframe src="https://leetcode.com/playground/EAaTWi42/shared" frameBorder="0" width="1000" height="800"></iframe>\n\nIf you feel it useful please upvote \uD83D\uDE0A\uD83D\uDE0A.\nIn case of any queries or suggestions please let me know in the comment section.
1
You have a **browser** of one tab where you start on the `homepage` and you can visit another `url`, get back in the history number of `steps` or move forward in the history number of `steps`. Implement the `BrowserHistory` class: * `BrowserHistory(string homepage)` Initializes the object with the `homepage` of the...
Count the frequency of each character. Loop over all character from 'a' to 'z' and append the character if it exists and decrease frequency by 1. Do the same from 'z' to 'a'. Keep repeating until the frequency of all characters is zero.
Dynamic Array | Explained | O(1) each operation | C++ | Python
design-browser-history
0
1
\n<iframe src="https://leetcode.com/playground/EAaTWi42/shared" frameBorder="0" width="1000" height="800"></iframe>\n\nIf you feel it useful please upvote \uD83D\uDE0A\uD83D\uDE0A.\nIn case of any queries or suggestions please let me know in the comment section.
1
Given an `m x n` binary matrix `mat`, return _the number of special positions in_ `mat`_._ A position `(i, j)` is called **special** if `mat[i][j] == 1` and all other elements in row `i` and column `j` are `0` (rows and columns are **0-indexed**). **Example 1:** **Input:** mat = \[\[1,0,0\],\[0,0,1\],\[1,0,0\]\] **O...
Use two stack one for back history and one for forward history and simulate the functions. Can you do faster by using different data structure ?
python3 Solution
design-browser-history
0
1
\n```\nclass BrowserHistory:\n\n def __init__(self, homepage: str):\n self.stack=[homepage]\n self.pointer=0\n\n def visit(self, url: str) -> None:\n self.stack=self.stack[:self.pointer+1]\n self.stack.append(url)\n self.pointer=len(self.stack)-1\n\n def back(self, steps: int...
1
You have a **browser** of one tab where you start on the `homepage` and you can visit another `url`, get back in the history number of `steps` or move forward in the history number of `steps`. Implement the `BrowserHistory` class: * `BrowserHistory(string homepage)` Initializes the object with the `homepage` of the...
Count the frequency of each character. Loop over all character from 'a' to 'z' and append the character if it exists and decrease frequency by 1. Do the same from 'z' to 'a'. Keep repeating until the frequency of all characters is zero.
python3 Solution
design-browser-history
0
1
\n```\nclass BrowserHistory:\n\n def __init__(self, homepage: str):\n self.stack=[homepage]\n self.pointer=0\n\n def visit(self, url: str) -> None:\n self.stack=self.stack[:self.pointer+1]\n self.stack.append(url)\n self.pointer=len(self.stack)-1\n\n def back(self, steps: int...
1
Given an `m x n` binary matrix `mat`, return _the number of special positions in_ `mat`_._ A position `(i, j)` is called **special** if `mat[i][j] == 1` and all other elements in row `i` and column `j` are `0` (rows and columns are **0-indexed**). **Example 1:** **Input:** mat = \[\[1,0,0\],\[0,0,1\],\[1,0,0\]\] **O...
Use two stack one for back history and one for forward history and simulate the functions. Can you do faster by using different data structure ?
Python short and clean. DoublyLinkedList.
design-browser-history
0
1
# Approach\nTL;DR, Same as [Official LinkedList solution](https://leetcode.com/problems/design-browser-history/editorial/)\n\n# Complexity\n`__init__` and `visit` functions:\n- Time complexity: $$O(1)$$\n\n- Space complexity: $$O(1)$$\n\n`back` and `forward` functions:\n- Time complexity: $$O(k)$$, where `k is number o...
2
You have a **browser** of one tab where you start on the `homepage` and you can visit another `url`, get back in the history number of `steps` or move forward in the history number of `steps`. Implement the `BrowserHistory` class: * `BrowserHistory(string homepage)` Initializes the object with the `homepage` of the...
Count the frequency of each character. Loop over all character from 'a' to 'z' and append the character if it exists and decrease frequency by 1. Do the same from 'z' to 'a'. Keep repeating until the frequency of all characters is zero.
Python short and clean. DoublyLinkedList.
design-browser-history
0
1
# Approach\nTL;DR, Same as [Official LinkedList solution](https://leetcode.com/problems/design-browser-history/editorial/)\n\n# Complexity\n`__init__` and `visit` functions:\n- Time complexity: $$O(1)$$\n\n- Space complexity: $$O(1)$$\n\n`back` and `forward` functions:\n- Time complexity: $$O(k)$$, where `k is number o...
2
Given an `m x n` binary matrix `mat`, return _the number of special positions in_ `mat`_._ A position `(i, j)` is called **special** if `mat[i][j] == 1` and all other elements in row `i` and column `j` are `0` (rows and columns are **0-indexed**). **Example 1:** **Input:** mat = \[\[1,0,0\],\[0,0,1\],\[1,0,0\]\] **O...
Use two stack one for back history and one for forward history and simulate the functions. Can you do faster by using different data structure ?
[Python] Top down spaghetti solution - Authentic like Italian cuisine
paint-house-iii
0
1
# Intuition\nWe first need to understand the idea of having neighborhoods. It the most basic sense, it\'s the number of color switch between different neighbors plus 1.\n\nFor example, `houses = [1, 2, 2, 1, 1]`, number of `color` switchs are `2`, and we have `3` neighborhoods.\n\n# Approach\n<!-- Describe your approac...
1
There is a row of `m` houses in a small city, each house must be painted with one of the `n` colors (labeled from `1` to `n`), some houses that have been painted last summer should not be painted again. A neighborhood is a maximal group of continuous houses that are painted with the same color. * For example: `hous...
Represent the counts (odd or even) of vowels with a bitmask. Precompute the prefix xor for the bitmask of vowels and then get the longest valid substring.