title stringlengths 1 100 | titleSlug stringlengths 3 77 | Java int64 0 1 | Python3 int64 1 1 | content stringlengths 28 44.4k | voteCount int64 0 3.67k | question_content stringlengths 65 5k | question_hints stringclasses 970
values |
|---|---|---|---|---|---|---|---|
python approach o(n) | k-concatenation-maximum-sum | 0 | 1 | ### sorry if my explanation isn\'t good enough but i tried my best\n# Approach\n## can be done comparing that two cases (scenarios)\n## the first case\n- we take max contineous elements from the first array\n- ommitting the first negative ones\n- we take max continous elements from the last array\n- ommitting the last ... | 0 | Given an integer array `arr` and an integer `k`, modify the array by repeating it `k` times.
For example, if `arr = [1, 2]` and `k = 3` then the modified array will be `[1, 2, 1, 2, 1, 2]`.
Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be `0` and its sum in that cas... | Find all synonymous groups of words. Use union-find data structure. By backtracking, generate all possible statements. |
python approach o(n) | k-concatenation-maximum-sum | 0 | 1 | ### sorry if my explanation isn\'t good enough but i tried my best\n# Approach\n## can be done comparing that two cases (scenarios)\n## the first case\n- we take max contineous elements from the first array\n- ommitting the first negative ones\n- we take max continous elements from the last array\n- ommitting the last ... | 0 | Given an array `arr`, replace every element in that array with the greatest element among the elements to its right, and replace the last element with `-1`.
After doing so, return the array.
**Example 1:**
**Input:** arr = \[17,18,5,4,6,1\]
**Output:** \[18,6,6,6,1,-1\]
**Explanation:**
- index 0 --> the greatest e... | How to solve the problem for k=1 ? Use Kadane's algorithm for k=1. What are the possible cases for the answer ? The answer is the maximum between, the answer for k=1, the sum of the whole array multiplied by k, or the maximum suffix sum plus the maximum prefix sum plus (k-2) multiplied by the whole array sum for k > 1. |
Python || 92.21% Faster || Tarjan's Algorithm || Explained ||DFS | critical-connections-in-a-network | 0 | 1 | ```\nclass Solution:\n def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:\n def dfs(sv,parent,c):\n visited[sv]=1\n time[sv]=low[sv]=c\n c+=1\n for u in adj[sv]:\n if u==parent:\n continue\n ... | 1 | There are `n` servers numbered from `0` to `n - 1` connected by undirected server-to-server `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between servers `ai` and `bi`. Any server can reach other servers directly or indirectly through the network.
A _critical connection_ is ... | After dividing the array into K+1 sub-arrays, you will pick the sub-array with the minimum sum. Divide the sub-array into K+1 sub-arrays such that the minimum sub-array sum is as maximum as possible. Use binary search with greedy check. |
Python || 92.21% Faster || Tarjan's Algorithm || Explained ||DFS | critical-connections-in-a-network | 0 | 1 | ```\nclass Solution:\n def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:\n def dfs(sv,parent,c):\n visited[sv]=1\n time[sv]=low[sv]=c\n c+=1\n for u in adj[sv]:\n if u==parent:\n continue\n ... | 1 | Given an integer array `arr` and a target value `target`, return the integer `value` such that when we change all the integers larger than `value` in the given array to be equal to `value`, the sum of the array gets as close as possible (in absolute difference) to `target`.
In case of a tie, return the minimum such in... | Use Tarjan's algorithm. |
Simple - Intuitive Explanation - Beats 99% in theory as well as compute 😉[PYTHON] | critical-connections-in-a-network | 0 | 1 | # **Points to remember**\n1. About the **START**:\n\t* It\'s a continuous graph - there is a START vertex - we chose this and every other vertex can be visited/discovered by just doing Depth First Traversal from START\n\t* With respect to START every vertex will be visited/discovered/explored in the process of DFTraver... | 87 | There are `n` servers numbered from `0` to `n - 1` connected by undirected server-to-server `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between servers `ai` and `bi`. Any server can reach other servers directly or indirectly through the network.
A _critical connection_ is ... | After dividing the array into K+1 sub-arrays, you will pick the sub-array with the minimum sum. Divide the sub-array into K+1 sub-arrays such that the minimum sub-array sum is as maximum as possible. Use binary search with greedy check. |
Simple - Intuitive Explanation - Beats 99% in theory as well as compute 😉[PYTHON] | critical-connections-in-a-network | 0 | 1 | # **Points to remember**\n1. About the **START**:\n\t* It\'s a continuous graph - there is a START vertex - we chose this and every other vertex can be visited/discovered by just doing Depth First Traversal from START\n\t* With respect to START every vertex will be visited/discovered/explored in the process of DFTraver... | 87 | Given an integer array `arr` and a target value `target`, return the integer `value` such that when we change all the integers larger than `value` in the given array to be equal to `value`, the sum of the array gets as close as possible (in absolute difference) to `target`.
In case of a tie, return the minimum such in... | Use Tarjan's algorithm. |
Python 3 -> O(n log n) time and O(n) space using sort() & dictionary | minimum-absolute-difference | 0 | 1 | **Suggestions to make it better are always welcomed.**\n\nI almost thought I won\'t be able to solve this problem. But after thinking about using dictionary, I started figuring out.\n\nApproach:\n1. To find the minimum difference among numbers, we have to subtract ith number with all the remaining numbers. This will be... | 84 | Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows
* `a, b` are from `arr`
* `a < b`
* `b - a` equals to the minimum absolute difference o... | Solve the problem for every interval alone. Divide the problem into cases according to the position of the two intervals. |
Python 3 -> O(n log n) time and O(n) space using sort() & dictionary | minimum-absolute-difference | 0 | 1 | **Suggestions to make it better are always welcomed.**\n\nI almost thought I won\'t be able to solve this problem. But after thinking about using dictionary, I started figuring out.\n\nApproach:\n1. To find the minimum difference among numbers, we have to subtract ith number with all the remaining numbers. This will be... | 84 | Given an array of non-negative integers `arr`, you are initially positioned at `start` index of the array. When you are at index `i`, you can jump to `i + arr[i]` or `i - arr[i]`, check if you can reach to **any** index with value 0.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Inp... | Find the minimum absolute difference between two elements in the array. The minimum absolute difference must be a difference between two consecutive elements in the sorted array. |
easy python solution | minimum-absolute-difference | 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 an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows
* `a, b` are from `arr`
* `a < b`
* `b - a` equals to the minimum absolute difference o... | Solve the problem for every interval alone. Divide the problem into cases according to the position of the two intervals. |
easy python solution | minimum-absolute-difference | 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 an array of non-negative integers `arr`, you are initially positioned at `start` index of the array. When you are at index `i`, you can jump to `i + arr[i]` or `i - arr[i]`, check if you can reach to **any** index with value 0.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Inp... | Find the minimum absolute difference between two elements in the array. The minimum absolute difference must be a difference between two consecutive elements in the sorted array. |
✅ Beats 96.10% Solutions, ✅ Easy to understand Python solution by ✅ BOLT CODING ✅ | minimum-absolute-difference | 0 | 1 | Solution is pretty simple -- > we are using 2 loops , one to find the minimum absolute difference and 2nd to map which two differences match the minimum difference.\n\n# Complexity\n- Time complexity: O(nlog(n)) ---> as we are using only a single loop to find minimum difference and to append into list\n<!-- Add your ti... | 2 | Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows
* `a, b` are from `arr`
* `a < b`
* `b - a` equals to the minimum absolute difference o... | Solve the problem for every interval alone. Divide the problem into cases according to the position of the two intervals. |
✅ Beats 96.10% Solutions, ✅ Easy to understand Python solution by ✅ BOLT CODING ✅ | minimum-absolute-difference | 0 | 1 | Solution is pretty simple -- > we are using 2 loops , one to find the minimum absolute difference and 2nd to map which two differences match the minimum difference.\n\n# Complexity\n- Time complexity: O(nlog(n)) ---> as we are using only a single loop to find minimum difference and to append into list\n<!-- Add your ti... | 2 | Given an array of non-negative integers `arr`, you are initially positioned at `start` index of the array. When you are at index `i`, you can jump to `i + arr[i]` or `i - arr[i]`, check if you can reach to **any** index with value 0.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Inp... | Find the minimum absolute difference between two elements in the array. The minimum absolute difference must be a difference between two consecutive elements in the sorted array. |
Beats 100% (292ms), sort + single scan in Python | minimum-absolute-difference | 0 | 1 | Time complexity: sort dominates, and it\'s O(NlogN)\nSpace complexity: depends on how you implement sort, but it\'s typically O(N)\n\n```\nclass Solution:\n def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:\n arr.sort()\n res = []\n min_diff_so_far = float(\'inf\')\n for ... | 4 | Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows
* `a, b` are from `arr`
* `a < b`
* `b - a` equals to the minimum absolute difference o... | Solve the problem for every interval alone. Divide the problem into cases according to the position of the two intervals. |
Beats 100% (292ms), sort + single scan in Python | minimum-absolute-difference | 0 | 1 | Time complexity: sort dominates, and it\'s O(NlogN)\nSpace complexity: depends on how you implement sort, but it\'s typically O(N)\n\n```\nclass Solution:\n def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:\n arr.sort()\n res = []\n min_diff_so_far = float(\'inf\')\n for ... | 4 | Given an array of non-negative integers `arr`, you are initially positioned at `start` index of the array. When you are at index `i`, you can jump to `i + arr[i]` or `i - arr[i]`, check if you can reach to **any** index with value 0.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Inp... | Find the minimum absolute difference between two elements in the array. The minimum absolute difference must be a difference between two consecutive elements in the sorted array. |
Easy to Understand | Faster | Simple | Python Solution | minimum-absolute-difference | 0 | 1 | ```\nclass Solution:\n def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:\n arr.sort()\n m = float(\'inf\')\n out = []\n for i in range(1, len(arr)):\n prev = arr[i - 1]\n curr = abs(prev - arr[i])\n if curr < m:\n out = [[pr... | 17 | Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows
* `a, b` are from `arr`
* `a < b`
* `b - a` equals to the minimum absolute difference o... | Solve the problem for every interval alone. Divide the problem into cases according to the position of the two intervals. |
Easy to Understand | Faster | Simple | Python Solution | minimum-absolute-difference | 0 | 1 | ```\nclass Solution:\n def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:\n arr.sort()\n m = float(\'inf\')\n out = []\n for i in range(1, len(arr)):\n prev = arr[i - 1]\n curr = abs(prev - arr[i])\n if curr < m:\n out = [[pr... | 17 | Given an array of non-negative integers `arr`, you are initially positioned at `start` index of the array. When you are at index `i`, you can jump to `i + arr[i]` or `i - arr[i]`, check if you can reach to **any** index with value 0.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Inp... | Find the minimum absolute difference between two elements in the array. The minimum absolute difference must be a difference between two consecutive elements in the sorted array. |
✅✅✅ 98.98% faster python solution | minimum-absolute-difference | 0 | 1 | \n# Code\n```\nclass Solution:\n def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:\n l = len(arr)\n arr.sort()\n answer = [[arr[0], arr[1... | 2 | Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows
* `a, b` are from `arr`
* `a < b`
* `b - a` equals to the minimum absolute difference o... | Solve the problem for every interval alone. Divide the problem into cases according to the position of the two intervals. |
✅✅✅ 98.98% faster python solution | minimum-absolute-difference | 0 | 1 | \n# Code\n```\nclass Solution:\n def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:\n l = len(arr)\n arr.sort()\n answer = [[arr[0], arr[1... | 2 | Given an array of non-negative integers `arr`, you are initially positioned at `start` index of the array. When you are at index `i`, you can jump to `i + arr[i]` or `i - arr[i]`, check if you can reach to **any** index with value 0.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Inp... | Find the minimum absolute difference between two elements in the array. The minimum absolute difference must be a difference between two consecutive elements in the sorted array. |
Both CPP and Python | minimum-absolute-difference | 0 | 1 | \n```CPP []\nclass Solution \n{\npublic:\n vector<vector<int>> minimumAbsDifference(vector<int>& arr) \n {\n sort(arr.begin(),arr.end());\n \n int m = INT_MAX;\n for(int i=0;i<arr.size()-1;i++)\n m = min(m,arr[i+1]-arr[i]);\n\n vector<vector<int>> ans;\n for(in... | 2 | Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows
* `a, b` are from `arr`
* `a < b`
* `b - a` equals to the minimum absolute difference o... | Solve the problem for every interval alone. Divide the problem into cases according to the position of the two intervals. |
Both CPP and Python | minimum-absolute-difference | 0 | 1 | \n```CPP []\nclass Solution \n{\npublic:\n vector<vector<int>> minimumAbsDifference(vector<int>& arr) \n {\n sort(arr.begin(),arr.end());\n \n int m = INT_MAX;\n for(int i=0;i<arr.size()-1;i++)\n m = min(m,arr[i+1]-arr[i]);\n\n vector<vector<int>> ans;\n for(in... | 2 | Given an array of non-negative integers `arr`, you are initially positioned at `start` index of the array. When you are at index `i`, you can jump to `i + arr[i]` or `i - arr[i]`, check if you can reach to **any** index with value 0.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Inp... | Find the minimum absolute difference between two elements in the array. The minimum absolute difference must be a difference between two consecutive elements in the sorted array. |
Math | ugly-number-iii | 0 | 1 | Here we count the occurence of number which are multiple of a,b,c which are less than equal to val. \nThe main principle used here is\n> **The principle of inclusion and exclusion (PIE)** is a counting technique that computes the number of elements that satisfy at least one of several properties while guaranteeing that... | 4 | An **ugly number** is a positive integer that is divisible by `a`, `b`, or `c`.
Given four integers `n`, `a`, `b`, and `c`, return the `nth` **ugly number**.
**Example 1:**
**Input:** n = 3, a = 2, b = 3, c = 5
**Output:** 4
**Explanation:** The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.
**Example 2:... | Traverse the tree using depth first search. Find for every node the sum of values of its sub-tree. Traverse the tree again from the root and return once you reach a node with zero sum of values in its sub-tree. |
Math | ugly-number-iii | 0 | 1 | Here we count the occurence of number which are multiple of a,b,c which are less than equal to val. \nThe main principle used here is\n> **The principle of inclusion and exclusion (PIE)** is a counting technique that computes the number of elements that satisfy at least one of several properties while guaranteeing that... | 4 | Given an equation, represented by `words` on the left side and the `result` on the right side.
You need to check if the equation is solvable under the following rules:
* Each character is decoded as one digit (0 - 9).
* No two characters can map to the same digit.
* Each `words[i]` and `result` are decoded as o... | Write a function f(k) to determine how many ugly numbers smaller than k. As f(k) is non-decreasing, try binary search. Find all ugly numbers in [1, LCM(a, b, c)] (LCM is Least Common Multiple). Use inclusion-exclusion principle to expand the result. |
[Python3] inconsistent definition of "ugly numbers" | ugly-number-iii | 0 | 1 | The term "ugly number" seems to reflect a poorly-defined concept. Upon Googling it, I can only find it in a few places such as LC, GFG, etc. Even in the few posts on LC, the concept varies. For example, in [263. Ugly Number](https://leetcode.com/problems/ugly-number/), an ugly number is a positive integer whose only fa... | 39 | An **ugly number** is a positive integer that is divisible by `a`, `b`, or `c`.
Given four integers `n`, `a`, `b`, and `c`, return the `nth` **ugly number**.
**Example 1:**
**Input:** n = 3, a = 2, b = 3, c = 5
**Output:** 4
**Explanation:** The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.
**Example 2:... | Traverse the tree using depth first search. Find for every node the sum of values of its sub-tree. Traverse the tree again from the root and return once you reach a node with zero sum of values in its sub-tree. |
[Python3] inconsistent definition of "ugly numbers" | ugly-number-iii | 0 | 1 | The term "ugly number" seems to reflect a poorly-defined concept. Upon Googling it, I can only find it in a few places such as LC, GFG, etc. Even in the few posts on LC, the concept varies. For example, in [263. Ugly Number](https://leetcode.com/problems/ugly-number/), an ugly number is a positive integer whose only fa... | 39 | Given an equation, represented by `words` on the left side and the `result` on the right side.
You need to check if the equation is solvable under the following rules:
* Each character is decoded as one digit (0 - 9).
* No two characters can map to the same digit.
* Each `words[i]` and `result` are decoded as o... | Write a function f(k) to determine how many ugly numbers smaller than k. As f(k) is non-decreasing, try binary search. Find all ugly numbers in [1, LCM(a, b, c)] (LCM is Least Common Multiple). Use inclusion-exclusion principle to expand the result. |
PYTHON | BRUTE FORCE TO OPTIMZIED SOL | FULL DETAILED EXPLANATION| | ugly-number-iii | 0 | 1 | \n# EXPLANATION BRUTE FORCE\n```\nBrute force is trying each number from 1 untill we get our nth ugly number\nNow we can improve this approach by using the idea that we need to get the nth ugly number which is divisible by a,b,or c\n\nSo we make a list of size 3 "times = [1,1,1]" having all values as 1 indicating the ... | 4 | An **ugly number** is a positive integer that is divisible by `a`, `b`, or `c`.
Given four integers `n`, `a`, `b`, and `c`, return the `nth` **ugly number**.
**Example 1:**
**Input:** n = 3, a = 2, b = 3, c = 5
**Output:** 4
**Explanation:** The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.
**Example 2:... | Traverse the tree using depth first search. Find for every node the sum of values of its sub-tree. Traverse the tree again from the root and return once you reach a node with zero sum of values in its sub-tree. |
PYTHON | BRUTE FORCE TO OPTIMZIED SOL | FULL DETAILED EXPLANATION| | ugly-number-iii | 0 | 1 | \n# EXPLANATION BRUTE FORCE\n```\nBrute force is trying each number from 1 untill we get our nth ugly number\nNow we can improve this approach by using the idea that we need to get the nth ugly number which is divisible by a,b,or c\n\nSo we make a list of size 3 "times = [1,1,1]" having all values as 1 indicating the ... | 4 | Given an equation, represented by `words` on the left side and the `result` on the right side.
You need to check if the equation is solvable under the following rules:
* Each character is decoded as one digit (0 - 9).
* No two characters can map to the same digit.
* Each `words[i]` and `result` are decoded as o... | Write a function f(k) to determine how many ugly numbers smaller than k. As f(k) is non-decreasing, try binary search. Find all ugly numbers in [1, LCM(a, b, c)] (LCM is Least Common Multiple). Use inclusion-exclusion principle to expand the result. |
Python Medium | ugly-number-iii | 0 | 1 | ```\nclass Solution:\n def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:\n\n\n lcm1 = math.lcm(a, b, c)\n lcm2 = math.lcm(a, b)\n lcm3 = math.lcm(a, c)\n lcm4 = math.lcm(b, c)\n\n l, r = min(a, b, c), max(a, b, c) * n\n\n\n while l < r:\n mid = (l + ... | 0 | An **ugly number** is a positive integer that is divisible by `a`, `b`, or `c`.
Given four integers `n`, `a`, `b`, and `c`, return the `nth` **ugly number**.
**Example 1:**
**Input:** n = 3, a = 2, b = 3, c = 5
**Output:** 4
**Explanation:** The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.
**Example 2:... | Traverse the tree using depth first search. Find for every node the sum of values of its sub-tree. Traverse the tree again from the root and return once you reach a node with zero sum of values in its sub-tree. |
Python Medium | ugly-number-iii | 0 | 1 | ```\nclass Solution:\n def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:\n\n\n lcm1 = math.lcm(a, b, c)\n lcm2 = math.lcm(a, b)\n lcm3 = math.lcm(a, c)\n lcm4 = math.lcm(b, c)\n\n l, r = min(a, b, c), max(a, b, c) * n\n\n\n while l < r:\n mid = (l + ... | 0 | Given an equation, represented by `words` on the left side and the `result` on the right side.
You need to check if the equation is solvable under the following rules:
* Each character is decoded as one digit (0 - 9).
* No two characters can map to the same digit.
* Each `words[i]` and `result` are decoded as o... | Write a function f(k) to determine how many ugly numbers smaller than k. As f(k) is non-decreasing, try binary search. Find all ugly numbers in [1, LCM(a, b, c)] (LCM is Least Common Multiple). Use inclusion-exclusion principle to expand the result. |
✔️ [Python3] UNION-FIND (❁´▽`❁)*✲゚*, Explained | smallest-string-with-swaps | 0 | 1 | **UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThe main idea here is to represent the string as a graph (indexes are nodes and pairs are edges). We can swap characters only if they connected with an edge. Since we can swap chars any amount of time within formed b... | 67 | You are given a string `s`, and an array of pairs of indices in the string `pairs` where `pairs[i] = [a, b]` indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given `pairs` **any number of times**.
Return the lexicographically smallest string that `s` can be chang... | Use dynamic programming. Let dp[i][j] be the solution for the sub-array from index i to index j. Notice that if we have S[i] == S[j] one transition could be just dp(i + 1, j + 1) because in the last turn we would have a palindrome and we can extend this palindrome from both sides, the other transitions are not too diff... |
[Python] Modified Disjoint Set Union with Explanation | smallest-string-with-swaps | 0 | 1 | ### Introduction\n\nGiven a string `s`, we need to find the minimum lexicographical arrangement of the characters in `s`, with the limitation that swaps in `s` are restricted to defined swaps between two indexes as per `pairs` (0-indexed).\n\nSince index pairs may overlap, it is important to know the full list of index... | 7 | You are given a string `s`, and an array of pairs of indices in the string `pairs` where `pairs[i] = [a, b]` indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given `pairs` **any number of times**.
Return the lexicographically smallest string that `s` can be chang... | Use dynamic programming. Let dp[i][j] be the solution for the sub-array from index i to index j. Notice that if we have S[i] == S[j] one transition could be just dp(i + 1, j + 1) because in the last turn we would have a palindrome and we can extend this palindrome from both sides, the other transitions are not too diff... |
python3 explained | smallest-string-with-swaps | 0 | 1 | ```\nclass UnionFind:\n def __init__(self, size):\n self.root = [i for i in range(size)]\n self.rank = [1] * size\n def find(self, x):\n if x == self.root[x]:\n return x\n self.root[x] = self.find(self.root[x])\n return self.root[x]\n def union(self, x, y):\n ... | 19 | You are given a string `s`, and an array of pairs of indices in the string `pairs` where `pairs[i] = [a, b]` indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given `pairs` **any number of times**.
Return the lexicographically smallest string that `s` can be chang... | Use dynamic programming. Let dp[i][j] be the solution for the sub-array from index i to index j. Notice that if we have S[i] == S[j] one transition could be just dp(i + 1, j + 1) because in the last turn we would have a palindrome and we can extend this palindrome from both sides, the other transitions are not too diff... |
Clean Python DFS | O( n log n ) | smallest-string-with-swaps | 0 | 1 | **Clean Python DFS | O( n log n )**\n\nThe code below presents a clean Python DFS solution for this problem. The algorithm works as follows:\n\n1. The initial idea is that each pair of swappable letters in "pairs" can be treated as an edge in a (undirected) graph. This works because, in the limit case, we could do bubb... | 18 | You are given a string `s`, and an array of pairs of indices in the string `pairs` where `pairs[i] = [a, b]` indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given `pairs` **any number of times**.
Return the lexicographically smallest string that `s` can be chang... | Use dynamic programming. Let dp[i][j] be the solution for the sub-array from index i to index j. Notice that if we have S[i] == S[j] one transition could be just dp(i + 1, j + 1) because in the last turn we would have a palindrome and we can extend this palindrome from both sides, the other transitions are not too diff... |
[Python3] Union-find + Priority Queue (Heap). Easy to understand | smallest-string-with-swaps | 0 | 1 | Method 1: Union-find + sort\nTC: O(nlogn)\nSC: O(n)\n```\nclass UnionFind:\n def __init__(self, size: int):\n self.root = [i for i in range(size)]\n self.rank = [1 for _ in range(size)]\n \n def find(self, x: int) -> int:\n if x == self.root[x]:\n return x\n \n ... | 10 | You are given a string `s`, and an array of pairs of indices in the string `pairs` where `pairs[i] = [a, b]` indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given `pairs` **any number of times**.
Return the lexicographically smallest string that `s` can be chang... | Use dynamic programming. Let dp[i][j] be the solution for the sub-array from index i to index j. Notice that if we have S[i] == S[j] one transition could be just dp(i + 1, j + 1) because in the last turn we would have a palindrome and we can extend this palindrome from both sides, the other transitions are not too diff... |
🔥🔥🔥🔥🔥Easy Solution | JS | TS | Java | C++ | Python 🔥🔥🔥🔥🔥 | sort-items-by-groups-respecting-dependencies | 1 | 1 | ---\n\n\n---\n**Intuition:**\nTo solve this problem, we need to perform a topological sort considering the constraints from both the `group` and `beforeItems` arrays. The items within the same group shoul... | 6 | There are `n` items each belonging to zero or one of `m` groups where `group[i]` is the group that the `i`\-th item belongs to and it's equal to `-1` if the `i`\-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.
Return a sorted list of the items such that... | null |
🔥🔥🔥🔥🔥Easy Solution | JS | TS | Java | C++ | Python 🔥🔥🔥🔥🔥 | sort-items-by-groups-respecting-dependencies | 1 | 1 | ---\n\n\n---\n**Intuition:**\nTo solve this problem, we need to perform a topological sort considering the constraints from both the `group` and `beforeItems` arrays. The items within the same group shoul... | 6 | You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows:
* Characters (`'a'` to `'i'`) are represented by (`'1'` to `'9'`) respectively.
* Characters (`'j'` to `'z'`) are represented by (`'10#'` to `'26#'`) respectively.
Return _the string formed after ... | Think of it as a graph problem. We need to find a topological order on the dependency graph. Build two graphs, one for the groups and another for the items. |
Python3 Solution | sort-items-by-groups-respecting-dependencies | 0 | 1 | \n```\nclass Solution:\n def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:\n for i in range(n):\n if group[i]==-1:\n group[i]=i+m\n\n graph0={}\n seen0=[0]*(m+n)\n graph1={}\n seen1=[0]*n\n\n for i,x i... | 4 | There are `n` items each belonging to zero or one of `m` groups where `group[i]` is the group that the `i`\-th item belongs to and it's equal to `-1` if the `i`\-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.
Return a sorted list of the items such that... | null |
Python3 Solution | sort-items-by-groups-respecting-dependencies | 0 | 1 | \n```\nclass Solution:\n def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:\n for i in range(n):\n if group[i]==-1:\n group[i]=i+m\n\n graph0={}\n seen0=[0]*(m+n)\n graph1={}\n seen1=[0]*n\n\n for i,x i... | 4 | You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows:
* Characters (`'a'` to `'i'`) are represented by (`'1'` to `'9'`) respectively.
* Characters (`'j'` to `'z'`) are represented by (`'10#'` to `'26#'`) respectively.
Return _the string formed after ... | Think of it as a graph problem. We need to find a topological order on the dependency graph. Build two graphs, one for the groups and another for the items. |
🚒 🚒 Two Level Topological Sorting 🕸️🕸️✅ | sort-items-by-groups-respecting-dependencies | 0 | 1 | # Intuition\nTo solve this problem, topological sorting should be done at two levels, one topological sorting to sort the `groups`, and the other to sort the `items` with in a `group`.\n\n# Approach\n1. Assign unique groups to the items that are not part of any group to maintain consistency. i.e assign `group[item_id]`... | 1 | There are `n` items each belonging to zero or one of `m` groups where `group[i]` is the group that the `i`\-th item belongs to and it's equal to `-1` if the `i`\-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.
Return a sorted list of the items such that... | null |
🚒 🚒 Two Level Topological Sorting 🕸️🕸️✅ | sort-items-by-groups-respecting-dependencies | 0 | 1 | # Intuition\nTo solve this problem, topological sorting should be done at two levels, one topological sorting to sort the `groups`, and the other to sort the `items` with in a `group`.\n\n# Approach\n1. Assign unique groups to the items that are not part of any group to maintain consistency. i.e assign `group[item_id]`... | 1 | You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows:
* Characters (`'a'` to `'i'`) are represented by (`'1'` to `'9'`) respectively.
* Characters (`'j'` to `'z'`) are represented by (`'10#'` to `'26#'`) respectively.
Return _the string formed after ... | Think of it as a graph problem. We need to find a topological order on the dependency graph. Build two graphs, one for the groups and another for the items. |
Python toposort | sort-items-by-groups-respecting-dependencies | 0 | 1 | # Intuition\nToposort it. Return [] if failed.\nSort each groups first then sort all groups.\n\n# Code\n```\nclass Solution:\n def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:\n\n # Transform group definition\n group = [ g - (g==-1) * i for i, g in enume... | 1 | There are `n` items each belonging to zero or one of `m` groups where `group[i]` is the group that the `i`\-th item belongs to and it's equal to `-1` if the `i`\-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.
Return a sorted list of the items such that... | null |
Python toposort | sort-items-by-groups-respecting-dependencies | 0 | 1 | # Intuition\nToposort it. Return [] if failed.\nSort each groups first then sort all groups.\n\n# Code\n```\nclass Solution:\n def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:\n\n # Transform group definition\n group = [ g - (g==-1) * i for i, g in enume... | 1 | You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows:
* Characters (`'a'` to `'i'`) are represented by (`'1'` to `'9'`) respectively.
* Characters (`'j'` to `'z'`) are represented by (`'10#'` to `'26#'`) respectively.
Return _the string formed after ... | Think of it as a graph problem. We need to find a topological order on the dependency graph. Build two graphs, one for the groups and another for the items. |
Python | Easy to Understand | Dependency Nodes | Two-Level Topological Sort | Optimal | sort-items-by-groups-respecting-dependencies | 0 | 1 | # Python | Easy to Understand | Dependency Nodes | Two-Level Topological Sort | Optimal\n```\nclass Solution:\n def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:\n def topo_sort(points, pre, suc):\n order = []\n sources = [p for p in points i... | 1 | There are `n` items each belonging to zero or one of `m` groups where `group[i]` is the group that the `i`\-th item belongs to and it's equal to `-1` if the `i`\-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.
Return a sorted list of the items such that... | null |
Python | Easy to Understand | Dependency Nodes | Two-Level Topological Sort | Optimal | sort-items-by-groups-respecting-dependencies | 0 | 1 | # Python | Easy to Understand | Dependency Nodes | Two-Level Topological Sort | Optimal\n```\nclass Solution:\n def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:\n def topo_sort(points, pre, suc):\n order = []\n sources = [p for p in points i... | 1 | You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows:
* Characters (`'a'` to `'i'`) are represented by (`'1'` to `'9'`) respectively.
* Characters (`'j'` to `'z'`) are represented by (`'10#'` to `'26#'`) respectively.
Return _the string formed after ... | Think of it as a graph problem. We need to find a topological order on the dependency graph. Build two graphs, one for the groups and another for the items. |
python 100% faster | two topological sort | simple code | sort-items-by-groups-respecting-dependencies | 0 | 1 | # Approach\nIf we ignore the condition that elements of the same group must be together it is a classical problem solvable with topological sorting, now to add the other constraint we can make two separate networks and then run a topological sorting for each graph.\n\nThe first network will be a set of $m$ disjoint gra... | 1 | There are `n` items each belonging to zero or one of `m` groups where `group[i]` is the group that the `i`\-th item belongs to and it's equal to `-1` if the `i`\-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.
Return a sorted list of the items such that... | null |
python 100% faster | two topological sort | simple code | sort-items-by-groups-respecting-dependencies | 0 | 1 | # Approach\nIf we ignore the condition that elements of the same group must be together it is a classical problem solvable with topological sorting, now to add the other constraint we can make two separate networks and then run a topological sorting for each graph.\n\nThe first network will be a set of $m$ disjoint gra... | 1 | You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows:
* Characters (`'a'` to `'i'`) are represented by (`'1'` to `'9'`) respectively.
* Characters (`'j'` to `'z'`) are represented by (`'10#'` to `'26#'`) respectively.
Return _the string formed after ... | Think of it as a graph problem. We need to find a topological order on the dependency graph. Build two graphs, one for the groups and another for the items. |
✅ 97.18% 2-Approaches Topological Sorting | sort-items-by-groups-respecting-dependencies | 0 | 1 | # Problem Understanding\n\nIn the "Sort Items by Groups Respecting Dependencies" problem, we are given `n` items each belonging to one of `m` groups or to no group at all. Each item might have dependencies, which are other items that need to come before it in a sorted order. The task is to return a sorted list of items... | 28 | There are `n` items each belonging to zero or one of `m` groups where `group[i]` is the group that the `i`\-th item belongs to and it's equal to `-1` if the `i`\-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.
Return a sorted list of the items such that... | null |
✅ 97.18% 2-Approaches Topological Sorting | sort-items-by-groups-respecting-dependencies | 0 | 1 | # Problem Understanding\n\nIn the "Sort Items by Groups Respecting Dependencies" problem, we are given `n` items each belonging to one of `m` groups or to no group at all. Each item might have dependencies, which are other items that need to come before it in a sorted order. The task is to return a sorted list of items... | 28 | You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows:
* Characters (`'a'` to `'i'`) are represented by (`'1'` to `'9'`) respectively.
* Characters (`'j'` to `'z'`) are represented by (`'10#'` to `'26#'`) respectively.
Return _the string formed after ... | Think of it as a graph problem. We need to find a topological order on the dependency graph. Build two graphs, one for the groups and another for the items. |
2x Kahn's Algorithm, explained! (Python3 | 97.8% S, 99.6% M) | sort-items-by-groups-respecting-dependencies | 0 | 1 | # Intuition\n\nWe want to order by precedence and also order by grouping. This type of ordering is similar to course schedule prerequisite problems, so I got the idea of using topological sort from that. \n\nFor topological sort, we can use DFS or kahn\'s algorithm, but I chose kahn\'s algorithm since its more intuitiv... | 1 | There are `n` items each belonging to zero or one of `m` groups where `group[i]` is the group that the `i`\-th item belongs to and it's equal to `-1` if the `i`\-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.
Return a sorted list of the items such that... | null |
2x Kahn's Algorithm, explained! (Python3 | 97.8% S, 99.6% M) | sort-items-by-groups-respecting-dependencies | 0 | 1 | # Intuition\n\nWe want to order by precedence and also order by grouping. This type of ordering is similar to course schedule prerequisite problems, so I got the idea of using topological sort from that. \n\nFor topological sort, we can use DFS or kahn\'s algorithm, but I chose kahn\'s algorithm since its more intuitiv... | 1 | You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows:
* Characters (`'a'` to `'i'`) are represented by (`'1'` to `'9'`) respectively.
* Characters (`'j'` to `'z'`) are represented by (`'10#'` to `'26#'`) respectively.
Return _the string formed after ... | Think of it as a graph problem. We need to find a topological order on the dependency graph. Build two graphs, one for the groups and another for the items. |
simple solution with dynamic levels + references | design-skiplist | 0 | 1 | Info that helped me to solve this problem:\n- https://leetcode.com/problems/design-skiplist/discuss/698146/Things-that-helped-me-solve-this-problem\n- https://cw.fel.cvut.cz/old/_media/courses/a4b36acm/maraton2015skiplist.pdf\n- https://cglab.ca/~morin/teaching/5408/refs/p90b.pdf\n\nFollowing implementation is pretty s... | 11 | Design a **Skiplist** without using any built-in libraries.
A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists ... | null |
simple solution with dynamic levels + references | design-skiplist | 0 | 1 | Info that helped me to solve this problem:\n- https://leetcode.com/problems/design-skiplist/discuss/698146/Things-that-helped-me-solve-this-problem\n- https://cw.fel.cvut.cz/old/_media/courses/a4b36acm/maraton2015skiplist.pdf\n- https://cglab.ca/~morin/teaching/5408/refs/p90b.pdf\n\nFollowing implementation is pretty s... | 11 | You are given an `m x n` binary matrix `mat` of `1`'s (representing soldiers) and `0`'s (representing civilians). The soldiers are positioned **in front** of the civilians. That is, all the `1`'s will appear to the **left** of all the `0`'s in each row.
A row `i` is **weaker** than a row `j` if one of the following is... | null |
[Python3] skiplist | design-skiplist | 0 | 1 | \n```\nclass ListNode: \n def __init__(self, val, cnt=1, next=None, down=None): \n self.val = val\n self.cnt = cnt\n self.next = next\n self.down = down\n\n \nclass Skiplist:\n\n def __init__(self):\n self.head = ListNode(-inf)\n self.p = 1/4 \n \n de... | 5 | Design a **Skiplist** without using any built-in libraries.
A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists ... | null |
[Python3] skiplist | design-skiplist | 0 | 1 | \n```\nclass ListNode: \n def __init__(self, val, cnt=1, next=None, down=None): \n self.val = val\n self.cnt = cnt\n self.next = next\n self.down = down\n\n \nclass Skiplist:\n\n def __init__(self):\n self.head = ListNode(-inf)\n self.p = 1/4 \n \n de... | 5 | You are given an `m x n` binary matrix `mat` of `1`'s (representing soldiers) and `0`'s (representing civilians). The soldiers are positioned **in front** of the civilians. That is, all the `1`'s will appear to the **left** of all the `0`'s in each row.
A row `i` is **weaker** than a row `j` if one of the following is... | null |
Python 3: Clean Implementation, Next/Down Convention | design-skiplist | 0 | 1 | # Intuition\n\nThe gif is a bit misleading; the core parts of a skiplist are\n* the skiplist has `levels` linked lists\n* each list has a subset of the values in the list below it (about half usually)\n* for each node in a higher list (subset), it has a pointer to the corresponding node in the next level down\n * so i... | 0 | Design a **Skiplist** without using any built-in libraries.
A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists ... | null |
Python 3: Clean Implementation, Next/Down Convention | design-skiplist | 0 | 1 | # Intuition\n\nThe gif is a bit misleading; the core parts of a skiplist are\n* the skiplist has `levels` linked lists\n* each list has a subset of the values in the list below it (about half usually)\n* for each node in a higher list (subset), it has a pointer to the corresponding node in the next level down\n * so i... | 0 | You are given an `m x n` binary matrix `mat` of `1`'s (representing soldiers) and `0`'s (representing civilians). The soldiers are positioned **in front** of the civilians. That is, all the `1`'s will appear to the **left** of all the `0`'s in each row.
A row `i` is **weaker** than a row `j` if one of the following is... | null |
Super simple defaultdict solution that beats 100% | design-skiplist | 1 | 1 | # Code\n```\nclass Skiplist:\n\n def __init__(self):\n self.skiplist = defaultdict(int)\n\n def search(self, target: int) -> bool:\n return self.skiplist[target] > 0\n\n def add(self, num: int) -> None:\n self.skiplist[num] += 1\n\n def erase(self, num: int) -> bool:\n if self.sk... | 0 | Design a **Skiplist** without using any built-in libraries.
A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists ... | null |
Super simple defaultdict solution that beats 100% | design-skiplist | 1 | 1 | # Code\n```\nclass Skiplist:\n\n def __init__(self):\n self.skiplist = defaultdict(int)\n\n def search(self, target: int) -> bool:\n return self.skiplist[target] > 0\n\n def add(self, num: int) -> None:\n self.skiplist[num] += 1\n\n def erase(self, num: int) -> bool:\n if self.sk... | 0 | You are given an `m x n` binary matrix `mat` of `1`'s (representing soldiers) and `0`'s (representing civilians). The soldiers are positioned **in front** of the civilians. That is, all the `1`'s will appear to the **left** of all the `0`'s in each row.
A row `i` is **weaker** than a row `j` if one of the following is... | null |
(Python3) Readable version (hopefully) | design-skiplist | 0 | 1 | \n```\nfrom random import getrandbits\n\n\nclass SkipNode:\n __slots__ = "prev", "next", "child", "value"\n\n def __init__(self, prev=None, next=None, child=None, value=-float("inf")):\n self.prev = prev\n self.next = next\n self.child = child\n self.value = value\n if next:\n ... | 0 | Design a **Skiplist** without using any built-in libraries.
A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists ... | null |
(Python3) Readable version (hopefully) | design-skiplist | 0 | 1 | \n```\nfrom random import getrandbits\n\n\nclass SkipNode:\n __slots__ = "prev", "next", "child", "value"\n\n def __init__(self, prev=None, next=None, child=None, value=-float("inf")):\n self.prev = prev\n self.next = next\n self.child = child\n self.value = value\n if next:\n ... | 0 | You are given an `m x n` binary matrix `mat` of `1`'s (representing soldiers) and `0`'s (representing civilians). The soldiers are positioned **in front** of the civilians. That is, all the `1`'s will appear to the **left** of all the `0`'s in each row.
A row `i` is **weaker** than a row `j` if one of the following is... | null |
Simple to understand solution with level lists!!! + 2 solutions | design-skiplist | 0 | 1 | \n```\nclass ListNode:\n def __init__(self, val=0, counter= 1, next=[]):\n self.val = val\n se... | 0 | Design a **Skiplist** without using any built-in libraries.
A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists ... | null |
Simple to understand solution with level lists!!! + 2 solutions | design-skiplist | 0 | 1 | \n```\nclass ListNode:\n def __init__(self, val=0, counter= 1, next=[]):\n self.val = val\n se... | 0 | You are given an `m x n` binary matrix `mat` of `1`'s (representing soldiers) and `0`'s (representing civilians). The soldiers are positioned **in front** of the civilians. That is, all the `1`'s will appear to the **left** of all the `0`'s in each row.
A row `i` is **weaker** than a row `j` if one of the following is... | null |
Super simple defaultdict Python solution that beats 100% | design-skiplist | 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 | Design a **Skiplist** without using any built-in libraries.
A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists ... | null |
Super simple defaultdict Python solution that beats 100% | design-skiplist | 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 `m x n` binary matrix `mat` of `1`'s (representing soldiers) and `0`'s (representing civilians). The soldiers are positioned **in front** of the civilians. That is, all the `1`'s will appear to the **left** of all the `0`'s in each row.
A row `i` is **weaker** than a row `j` if one of the following is... | null |
Design skiplist | design-skiplist | 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 | Design a **Skiplist** without using any built-in libraries.
A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists ... | null |
Design skiplist | design-skiplist | 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 `m x n` binary matrix `mat` of `1`'s (representing soldiers) and `0`'s (representing civilians). The soldiers are positioned **in front** of the civilians. That is, all the `1`'s will appear to the **left** of all the `0`'s in each row.
A row `i` is **weaker** than a row `j` if one of the following is... | null |
Simple Python 1 liner | unique-number-of-occurrences | 0 | 1 | \n# Code\n```\nclass Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n return len(set(Counter(arr).values())) == len(Counter(arr).values())\n``` | 2 | Given an array of integers `arr`, return `true` _if the number of occurrences of each value in the array is **unique** or_ `false` _otherwise_.
**Example 1:**
**Input:** arr = \[1,2,2,1,1,3\]
**Output:** true
**Explanation:** The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of oc... | null |
Simple Python 1 liner | unique-number-of-occurrences | 0 | 1 | \n# Code\n```\nclass Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n return len(set(Counter(arr).values())) == len(Counter(arr).values())\n``` | 2 | There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial com... | Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value. |
Take it easy ! | unique-number-of-occurrences | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal appears to be checking whether the number of occurrences of each element in the given list (arr) is unique.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach involves iterating through each elem... | 1 | Given an array of integers `arr`, return `true` _if the number of occurrences of each value in the array is **unique** or_ `false` _otherwise_.
**Example 1:**
**Input:** arr = \[1,2,2,1,1,3\]
**Output:** true
**Explanation:** The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of oc... | null |
Take it easy ! | unique-number-of-occurrences | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal appears to be checking whether the number of occurrences of each element in the given list (arr) is unique.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach involves iterating through each elem... | 1 | There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial com... | Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value. |
Python3|| O(N^2)||Runtime 61 ms Beats 64.37% Memory 14.1 MB Beats 32.48% | unique-number-of-occurrences | 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^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(N)\n<!-- Add your space complexity here... | 1 | Given an array of integers `arr`, return `true` _if the number of occurrences of each value in the array is **unique** or_ `false` _otherwise_.
**Example 1:**
**Input:** arr = \[1,2,2,1,1,3\]
**Output:** true
**Explanation:** The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of oc... | null |
Python3|| O(N^2)||Runtime 61 ms Beats 64.37% Memory 14.1 MB Beats 32.48% | unique-number-of-occurrences | 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^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(N)\n<!-- Add your space complexity here... | 1 | There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial com... | Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value. |
[Python3] Sliding Window - Two ways to implement - Easy to Understand | get-equal-substrings-within-budget | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here... | 4 | You are given two strings `s` and `t` of the same length and an integer `maxCost`.
You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference between the ASCII values of the characters).
Return _the maximum length of a substring of... | null |
Python || Easy Clean Solution. Sliding Window. | get-equal-substrings-within-budget | 0 | 1 | # Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def equalSubstring(self, s: str, t: str, maxCost: int) -> int:\n left = ans = curr = 0\n for... | 4 | You are given two strings `s` and `t` of the same length and an integer `maxCost`.
You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference between the ASCII values of the characters).
Return _the maximum length of a substring of... | null |
PYTHON | SLIDING WINDOW | O(n) | WELL EXPLAINED | EASY | | get-equal-substrings-within-budget | 0 | 1 | # EXPLANATION\nThe idea is very simple we keep a sliding window which will contain the substring which we \ncan convert using maxCost\n\nNow the idea of sliding window is \n1. increase the window from right\n2. decrease the window from left when we cannot increase further\n\nwe use the same idea for our sliding window ... | 1 | You are given two strings `s` and `t` of the same length and an integer `maxCost`.
You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference between the ASCII values of the characters).
Return _the maximum length of a substring of... | null |
Clean, easy to understand solution: prefix sum + sliding window | get-equal-substrings-within-budget | 0 | 1 | # Intuition\nI started calculating the cost at each step in a for loop, then I realized I could stop checking the items directly and focus on the costs. That gave me the idea to use a prefix sum.\n\n# Approach\n1. Calculate each cost and add it to a separate array\n2. Using that array, calculate the prefix sum and save... | 0 | You are given two strings `s` and `t` of the same length and an integer `maxCost`.
You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference between the ASCII values of the characters).
Return _the maximum length of a substring of... | null |
Fastest Python3 Sliding Window Solution | get-equal-substrings-within-budget | 0 | 1 | # Intuition\nConvert the problem to: Find Longest Subarray with Sum Less than K\n\n# Approach\nFirst calculate an array diff: store the differences between all entries.\nThen, find the longest subarray of diff with sum less than maxCost\nUse classic sliding window approach.\n\n# Complexity\n- Time complexity:\nO(n)\n\n... | 0 | You are given two strings `s` and `t` of the same length and an integer `maxCost`.
You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference between the ASCII values of the characters).
Return _the maximum length of a substring of... | null |
Simple Python Approach Beats 95.8% | get-equal-substrings-within-budget | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCreating a list with the differences between each character\'s ascii value\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSimple two pointer approach\n# Complexity\n- Time complexity:\n<!-- Add your time complexity ... | 0 | You are given two strings `s` and `t` of the same length and an integer `maxCost`.
You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference between the ASCII values of the characters).
Return _the maximum length of a substring of... | null |
Python3 | get-equal-substrings-within-budget | 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 two strings `s` and `t` of the same length and an integer `maxCost`.
You want to change `s` to `t`. Changing the `ith` character of `s` to `ith` character of `t` costs `|s[i] - t[i]|` (i.e., the absolute difference between the ASCII values of the characters).
Return _the maximum length of a substring of... | null |
✅Python 2D Stack implementation Easy + Accurate + Concise✅ | remove-all-adjacent-duplicates-in-string-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. -->\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 a string `s` and an integer `k`, a `k` **duplicate removal** consists of choosing `k` adjacent and equal letters from `s` and removing them, causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make `k` **duplicate removals** on `s` until we no longer can.
... | null |
✅Python 2D Stack implementation Easy + Accurate + Concise✅ | remove-all-adjacent-duplicates-in-string-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. -->\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 have a keyboard layout as shown above in the **X-Y** plane, where each English uppercase letter is located at some coordinate.
* For example, the letter `'A'` is located at coordinate `(0, 0)`, the letter `'B'` is located at coordinate `(0, 1)`, the letter `'P'` is located at coordinate `(2, 3)` and the letter `... | Use a stack to store the characters, when there are k same characters, delete them. To make it more efficient, use a pair to store the value and the count of each character. |
✅ Python Simple One Pass Solution | remove-all-adjacent-duplicates-in-string-ii | 0 | 1 | Once you have identified that **stack** solves this problem (this took me like 30mins to figure out :)...), the logic is quite straightforward. We just need to track consecutive occurences of a character. If **count** matches **k**, we pop the element from stack.\n\n```\nclass Solution:\n def removeDuplicates(self, ... | 96 | You are given a string `s` and an integer `k`, a `k` **duplicate removal** consists of choosing `k` adjacent and equal letters from `s` and removing them, causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make `k` **duplicate removals** on `s` until we no longer can.
... | null |
✅ Python Simple One Pass Solution | remove-all-adjacent-duplicates-in-string-ii | 0 | 1 | Once you have identified that **stack** solves this problem (this took me like 30mins to figure out :)...), the logic is quite straightforward. We just need to track consecutive occurences of a character. If **count** matches **k**, we pop the element from stack.\n\n```\nclass Solution:\n def removeDuplicates(self, ... | 96 | You have a keyboard layout as shown above in the **X-Y** plane, where each English uppercase letter is located at some coordinate.
* For example, the letter `'A'` is located at coordinate `(0, 0)`, the letter `'B'` is located at coordinate `(0, 1)`, the letter `'P'` is located at coordinate `(2, 3)` and the letter `... | Use a stack to store the characters, when there are k same characters, delete them. To make it more efficient, use a pair to store the value and the count of each character. |
Python || 98.58% Faster || Stack || O(n) Solution | remove-all-adjacent-duplicates-in-string-ii | 0 | 1 | ```\nclass Solution:\n def removeDuplicates(self, s: str, k: int) -> str:\n a=[]\n for i in s:\n if a and a[-1][0]==i:\n a[-1][1]+=1\n if a[-1][1]==k: a.pop()\n else: a.append([i,1])\n return \'\'.join(key*value for key, value in a) \n``... | 7 | You are given a string `s` and an integer `k`, a `k` **duplicate removal** consists of choosing `k` adjacent and equal letters from `s` and removing them, causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make `k` **duplicate removals** on `s` until we no longer can.
... | null |
Python || 98.58% Faster || Stack || O(n) Solution | remove-all-adjacent-duplicates-in-string-ii | 0 | 1 | ```\nclass Solution:\n def removeDuplicates(self, s: str, k: int) -> str:\n a=[]\n for i in s:\n if a and a[-1][0]==i:\n a[-1][1]+=1\n if a[-1][1]==k: a.pop()\n else: a.append([i,1])\n return \'\'.join(key*value for key, value in a) \n``... | 7 | You have a keyboard layout as shown above in the **X-Y** plane, where each English uppercase letter is located at some coordinate.
* For example, the letter `'A'` is located at coordinate `(0, 0)`, the letter `'B'` is located at coordinate `(0, 1)`, the letter `'P'` is located at coordinate `(2, 3)` and the letter `... | Use a stack to store the characters, when there are k same characters, delete them. To make it more efficient, use a pair to store the value and the count of each character. |
Ex-Amazon explains a solution with a video, Python, JavaScript, Java and C++ | remove-all-adjacent-duplicates-in-string-ii | 1 | 1 | # My youtube channel - KeetCode(Ex-Amazon)\nI create 147 videos for leetcode questions as of April 15, 2023. I believe my channel helps you prepare for the coming technical interviews. Please subscribe my channel!\n\n### Please subscribe my channel - KeetCode(Ex-Amazon) from here.\n\n**I created a video for this questi... | 1 | You are given a string `s` and an integer `k`, a `k` **duplicate removal** consists of choosing `k` adjacent and equal letters from `s` and removing them, causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make `k` **duplicate removals** on `s` until we no longer can.
... | null |
Ex-Amazon explains a solution with a video, Python, JavaScript, Java and C++ | remove-all-adjacent-duplicates-in-string-ii | 1 | 1 | # My youtube channel - KeetCode(Ex-Amazon)\nI create 147 videos for leetcode questions as of April 15, 2023. I believe my channel helps you prepare for the coming technical interviews. Please subscribe my channel!\n\n### Please subscribe my channel - KeetCode(Ex-Amazon) from here.\n\n**I created a video for this questi... | 1 | You have a keyboard layout as shown above in the **X-Y** plane, where each English uppercase letter is located at some coordinate.
* For example, the letter `'A'` is located at coordinate `(0, 0)`, the letter `'B'` is located at coordinate `(0, 1)`, the letter `'P'` is located at coordinate `(2, 3)` and the letter `... | Use a stack to store the characters, when there are k same characters, delete them. To make it more efficient, use a pair to store the value and the count of each character. |
Python || BFS | minimum-moves-to-reach-target-with-rotations | 0 | 1 | deque is defined as follows- \n(snake head x corrdinate, snake head y corrdinate, direction, iteration number)\nTime Complexity - O(n^2)\n\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n n=len(grid)\n seen=set()\n dq=deque()\n dq.append((0,1,"r",0))\n ... | 1 | In an `n*n` grid, there is a snake that spans 2 cells and starts moving from the top left corner at `(0, 0)` and `(0, 1)`. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at `(n-1, n-2)` and `(n-1, n-1)`.
In one move the snake can:
*... | Sort the given array. Remove the first and last 5% of the sorted array. |
Standard BFS in python3, not quite a hard one | minimum-moves-to-reach-target-with-rotations | 0 | 1 | # Code\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n n = len(grid)\n queue = [(0,1,0,0)]\n seen = set([(0,1,0)])\n for i,j,direc,step in queue:\n if (i,j,direc) == (n-1,n-1,0):\n return step\n if direc == 0:\n ... | 0 | In an `n*n` grid, there is a snake that spans 2 cells and starts moving from the top left corner at `(0, 0)` and `(0, 1)`. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at `(n-1, n-2)` and `(n-1, n-1)`.
In one move the snake can:
*... | Sort the given array. Remove the first and last 5% of the sorted array. |
DP but saving time and memory at the same time | minimum-moves-to-reach-target-with-rotations | 0 | 1 | # Code\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n n = len(grid)\n h = []\n for i in grid[0][1:]:\n if i == 0:\n h.append(0)\n else:\n h += [float(\'INF\')] * (n - 1 - len(h))\n break\n\n ... | 0 | In an `n*n` grid, there is a snake that spans 2 cells and starts moving from the top left corner at `(0, 0)` and `(0, 1)`. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at `(n-1, n-2)` and `(n-1, n-1)`.
In one move the snake can:
*... | Sort the given array. Remove the first and last 5% of the sorted array. |
✅3d dp solution || python | minimum-moves-to-reach-target-with-rotations | 0 | 1 | # Intuition\n please use bfs approach,my solution works but not optimize.\n\n# Code\n```\nclass Solution:\n\n def check(self,dp,grid,i,j,k,n):\n if(i==n-1 and j==n-1 and k==0):return 0\n if(min(i,j)<0 or max(i,j)>=n or grid[i][j]==1 or grid[i][j]==-1):return n*n\n # print(i,j,k,dp[i][j][k],"-... | 0 | In an `n*n` grid, there is a snake that spans 2 cells and starts moving from the top left corner at `(0, 0)` and `(0, 1)`. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at `(n-1, n-2)` and `(n-1, n-1)`.
In one move the snake can:
*... | Sort the given array. Remove the first and last 5% of the sorted array. |
Super Fast And Readable Python Solution Using Breadth First Search | minimum-moves-to-reach-target-with-rotations | 0 | 1 | # Intuition\nThis looks like a variation of the basic path planning problem where we must navigate a grid with obstacles. These are classically solved with breadth first search BFS as BFS reveals the shortest path to a node the very first time you reach it.\n\nThe twist here is that we have a snake that takes up two sq... | 0 | In an `n*n` grid, there is a snake that spans 2 cells and starts moving from the top left corner at `(0, 0)` and `(0, 1)`. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at `(n-1, n-2)` and `(n-1, n-1)`.
In one move the snake can:
*... | Sort the given array. Remove the first and last 5% of the sorted array. |
Easy to Understand | Faster | Simple | Python Solution | minimum-moves-to-reach-target-with-rotations | 0 | 1 | # Code\n```\nclass Solution:\n def minimumMoves(self, G: List[List[int]]) -> int:\n \tN, I, DP = len(G)-1, math.inf, [[math.inf]*2 for i in range(len(G)+1)]\n \tDP[N-1][0] = I if 1 in [G[N][N],G[N][N-1]] else 0\n \tfor j in range(N-2,-1,-1): DP[j][0] = (DP[j+1][0] + 1) if G[N][j] == 0 else I\n \tfor i,j ... | 0 | In an `n*n` grid, there is a snake that spans 2 cells and starts moving from the top left corner at `(0, 0)` and `(0, 1)`. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at `(n-1, n-2)` and `(n-1, n-1)`.
In one move the snake can:
*... | Sort the given array. Remove the first and last 5% of the sorted array. |
Time: O(n2)O(n2) Space: O(n2)O(n2) | minimum-moves-to-reach-target-with-rotations | 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 | In an `n*n` grid, there is a snake that spans 2 cells and starts moving from the top left corner at `(0, 0)` and `(0, 1)`. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at `(n-1, n-2)` and `(n-1, n-1)`.
In one move the snake can:
*... | Sort the given array. Remove the first and last 5% of the sorted array. |
Python (Simple Dijkstra's algorithm) | minimum-moves-to-reach-target-with-rotations | 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 | In an `n*n` grid, there is a snake that spans 2 cells and starts moving from the top left corner at `(0, 0)` and `(0, 1)`. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at `(n-1, n-2)` and `(n-1, n-1)`.
In one move the snake can:
*... | Sort the given array. Remove the first and last 5% of the sorted array. |
Python Straight BFS Solution | Easy to Understand | minimum-moves-to-reach-target-with-rotations | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nJust have right, down, clockwise and counter-clockwise as directions in the direction array and run a BFS\n\n# Code\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n side, queue = len(grid), deque([[(0, 0), (0, ... | 0 | In an `n*n` grid, there is a snake that spans 2 cells and starts moving from the top left corner at `(0, 0)` and `(0, 1)`. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at `(n-1, n-2)` and `(n-1, n-1)`.
In one move the snake can:
*... | Sort the given array. Remove the first and last 5% of the sorted array. |
Python 3 (BFS, DFS, and DP) (With Explanation) (beats 100.00%) | minimum-moves-to-reach-target-with-rotations | 0 | 1 | (Note to Reader: It will be helpful to have the code at the bottom visible separately on your screen while reading this explanation)\n\n_**BFS Explanation:**_\n\nThis program uses a BFS approach starting out from the top left corner. The program starts by saving the first position of the snake into list S. You do not n... | 9 | In an `n*n` grid, there is a snake that spans 2 cells and starts moving from the top left corner at `(0, 0)` and `(0, 1)`. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at `(n-1, n-2)` and `(n-1, n-1)`.
In one move the snake can:
*... | Sort the given array. Remove the first and last 5% of the sorted array. |
[Python3] Dijkstra's algo | minimum-moves-to-reach-target-with-rotations | 0 | 1 | \n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n n = len(grid)\n dist = {(0, 0, 0, 1): 0}\n pq = [(0, 0, 0, 0, 1)]\n while pq: \n x, i, j, ii, jj = heappop(pq)\n if i == n-1 and j == n-2 and ii == n-1 and jj == n-1: return x\n ... | 2 | In an `n*n` grid, there is a snake that spans 2 cells and starts moving from the top left corner at `(0, 0)` and `(0, 1)`. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at `(n-1, n-2)` and `(n-1, n-1)`.
In one move the snake can:
*... | Sort the given array. Remove the first and last 5% of the sorted array. |
Beats 100% || Full Explained || [Java/Python3/C++/JavaScript] | minimum-cost-to-move-chips-to-the-same-position | 1 | 1 | # Intuition\n1. Shift all the chips to neighbouring odd and even positon respectively, as the cost of moving chips to 2 position is 0.\n - So all the odd chips can be placed at a given odd position with 0 cost and same for even chips.\n - Distance between two odd place is 2 and distance between two even place is ... | 4 | We have `n` chips, where the position of the `ith` chip is `position[i]`.
We need to move all the chips to **the same position**. In one step, we can change the position of the `ith` chip from `position[i]` to:
* `position[i] + 2` or `position[i] - 2` with `cost = 0`.
* `position[i] + 1` or `position[i] - 1` with... | Using a hashmap, we can map the values of arr2 to their position in arr2. After, we can use a custom sorting function. |
Beats 100% || Full Explained || [Java/Python3/C++/JavaScript] | minimum-cost-to-move-chips-to-the-same-position | 1 | 1 | # Intuition\n1. Shift all the chips to neighbouring odd and even positon respectively, as the cost of moving chips to 2 position is 0.\n - So all the odd chips can be placed at a given odd position with 0 cost and same for even chips.\n - Distance between two odd place is 2 and distance between two even place is ... | 4 | A **matrix diagonal** is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the **matrix diagonal** starting from `mat[2][0]`, where `mat` is a `6 x 3` matrix, includes cells `mat[2][0]`, `ma... | The first move keeps the parity of the element as it is. The second move changes the parity of the element. Since the first move is free, if all the numbers have the same parity, the answer would be zero. Find the minimum cost to make all the numbers have the same parity. |
🚀🔥Leetcode 1218 | Python Solution + Video Tutorial 🎯🐍 | longest-arithmetic-subsequence-of-given-difference | 0 | 1 | # Intuition\nhttps://youtu.be/Ho7uSMTguCU\n<!-- Describe your first thoughts on how to solve this problem. -->\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# Code\n```\nclass Solution:... | 8 | Given an integer array `arr` and an integer `difference`, return the length of the longest subsequence in `arr` which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals `difference`.
A **subsequence** is a sequence that can be derived from `arr` by deleting some or n... | Do a postorder traversal. Then, if both subtrees contain a deepest leaf, you can mark this node as the answer (so far). The final node marked will be the correct answer. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.