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 |
|---|---|---|---|---|---|---|---|
Solution | divide-nodes-into-the-maximum-number-of-groups | 0 | 1 | \n# Code\n```\nfrom collections import deque \n\nclass Solution:\n def magnificentSets(self, n: int, edges: List[List[int]]) -> int:\n res = 0\n E = build_edges(edges)\n max_distances = {}\n for i in range(1, n+1):\n max_distance = bfs(i, E, n)\n if max_distance:\n ... | 0 | You are given a positive integer `n` representing the number of nodes in an **undirected** graph. The nodes are labeled from `1` to `n`.
You are also given a 2D integer array `edges`, where `edges[i] = [ai, bi]` indicates that there is a **bidirectional** edge between nodes `ai` and `bi`. **Notice** that the given gra... | null |
Beats 100% C++, Java, Python | maximum-value-of-a-string-in-an-array | 1 | 1 | # Intuition\nIterate through the collection of words and check if they satisfy the given conditions.\n\n# Approach\nEvery word we iterate through in the vector/ array/ list, we check:\nIf that word has a letter in it. If it does:\n We check if its length is greater than the maximum length we have come through so far... | 1 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1... | null |
Python3 solution using try and except block unique approach O(N),O(1) | maximum-value-of-a-string-in-an-array | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nwe have a variable m which stores the required ans,\nwe iterate through strts and try if given i can be converted to integer if it is not possible then a valueerror will show up and except block is entered here we will compare m with length of i and p... | 3 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1... | null |
[Python3] Beginner friendly solutions with explanation (re) | maximum-value-of-a-string-in-an-array | 0 | 1 | Using **regular expressions** you can check if a string **contains a digit** ```re.search(r\'\\d\', word)```, you can also check if a string **contains letters** ```re.search(r\'[a-z]\', word)```.\nFurther combining the conditions, we look for the value of an alphanumeric according to the task description.\n```\nclass ... | 2 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1... | null |
O(n) Easy solution in Python (100% Faster) | maximum-value-of-a-string-in-an-array | 0 | 1 | # Code\n```\nclass Solution:\n def maximumValue(self, strs: List[str]) -> int: \n max = 0 \n for i in strs:\n # check if we can convert string into integer\n try:\n if int(i)>max:\n max = int(i)\n # other wise take the length of string\... | 1 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1... | null |
Python simple and clear solution | maximum-value-of-a-string-in-an-array | 0 | 1 | # Approach\nSimply go through the array,\nThere are two cases: if the current string is a digit so we\'ll calculate the max between this digit and the current max, otherwise take the length of the string and calculate the max.\n\n# Complexity\n- Time complexity:\nO(n) - looping the array\n- Space complexity:\nO(1) - no... | 4 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1... | null |
Maximum Value of an String in an array | maximum-value-of-a-string-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)$$ --... | 1 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1... | null |
Easy Python Solution | maximum-value-of-a-string-in-an-array | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n Iterative\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexi... | 1 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1... | null |
Python 3 || 5 lines, w/ example || T/M: 90% / 61% | maximum-value-of-a-string-in-an-array | 0 | 1 | ```\nclass Solution:\n def maximumValue(self, strs: List[str]) -> int:\n # Example: strs = [\'alic3\', \'bob\', \'3\', \'7\', \'00000\']\n mx = 0\n # s s.isdigit() int(s) len(s) mx \n fo... | 4 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1... | null |
Recursive and Iterative | Python | maximum-value-of-a-string-in-an-array | 0 | 1 | \n# Iterative Code\n```\nclass Solution(object):\n def maximumValue(self, strs):\n max_ = 0\n for ch in strs:\n if ch.isdigit(): max_ = max(max_, int(ch))\n else: max_ = max(max_, len(ch))\n return max_\n```\n# Recursive Code\n```\nclass Solution(object):\n def maximumVa... | 11 | The **value** of an alphanumeric string can be defined as:
* The **numeric** representation of the string in base `10`, if it comprises of digits **only**.
* The **length** of the string, otherwise.
Given an array `strs` of alphanumeric strings, return _the **maximum value** of any string in_ `strs`.
**Example 1... | null |
Python3, Sort Positive Neighbors | maximum-star-sum-of-a-graph | 0 | 1 | # Approach\nWe are storing all positive neighbors for each node.\n\n# Complexity\n- Time complexity:\nO(N*log(N))\n\n- Space complexity:\nO(N**2)\n\n# Code\n```\nclass Solution:\n def maxStarSum(self, vals: List[int], edges: List[List[int]], k: int) -> int:\n if k==0: return max(vals) \n n=len(vals)\n ... | 1 | There is an undirected graph consisting of `n` nodes numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes the value of the `ith` node.
You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** ... | null |
[C++|Java|Python3] sorting | maximum-star-sum-of-a-graph | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/661cb4686dc915189ddbf0bc35fa51f408bf42ef) for solutions of biweekly 93. \n\n**Intuition**\nFor each node, we find the (at most) `k` largest adjacent nodes in `vals`. \n\n**Implementation**\n**C++**\n```\nclass Solution {\npublic:\n int maxStarSu... | 1 | There is an undirected graph consisting of `n` nodes numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes the value of the `ith` node.
You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** ... | null |
Beats 100% Python Simple Solution | maximum-star-sum-of-a-graph | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | There is an undirected graph consisting of `n` nodes numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes the value of the `ith` node.
You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** ... | null |
[Python] From Brute Force to Optimal. MinHeap O(V + E log(K)) solution. | maximum-star-sum-of-a-graph | 0 | 1 | # 1) Brute Force (using sort)\nBuild an adjacency list for each vertex in the graph. In a final pass, sort each adjacency list and compute the maximum possible star sum using at most K neighbors for each vertex.\n\n```Python\nclass Solution:\n def maxStarSum(self, vals: List[int], edges: List[List[int]], K: int) -> ... | 2 | There is an undirected graph consisting of `n` nodes numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes the value of the `ith` node.
You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** ... | null |
Python - MinHeap | maximum-star-sum-of-a-graph | 0 | 1 | ```\nclass Solution:\n def maxStarSum(self, vals: List[int], edges: List[List[int]], k: int) -> int:\n \n m = defaultdict(list) # For each node, we will have min heap of size k which stores values # of Top-K nodes it is conne... | 6 | There is an undirected graph consisting of `n` nodes numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes the value of the `ith` node.
You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** ... | null |
✅ [PYTHON] ✅ SIMPLE SOLUTION | | maximum-star-sum-of-a-graph | 0 | 1 | # Code\n```\nclass Solution:\n def maxStarSum(self, v: List[int], edges: List[List[int]], k: int) -> int:\n n = len(v)\n g = defaultdict(list)\n for s,d in edges:\n g[s].append([v[d],d])\n g[d].append([v[s],s])\n \n ms = -inf\n \n for z in range(... | 2 | There is an undirected graph consisting of `n` nodes numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes the value of the `ith` node.
You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** ... | null |
✅ Simple Python Solution - Sort reverse | maximum-star-sum-of-a-graph | 0 | 1 | # Intuition\nGet a list of all the neighbours, then sort them in descending order\n\n\n# Code\n```\nclass Solution:\n def maxStarSum(self, vals: List[int], edges: List[List[int]], k: int) -> int:\n graph = defaultdict(list)\n for start, end in edges:\n if vals[end] > 0:\n grap... | 2 | There is an undirected graph consisting of `n` nodes numbered from `0` to `n - 1`. You are given a **0-indexed** integer array `vals` of length `n` where `vals[i]` denotes the value of the `ith` node.
You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** ... | null |
beats 90% in python | frog-jump-ii | 0 | 1 | \n```\nclass Solution:\n def maxJump(self, stones: List[int]) -> int:\n if len(stones)==2:\n return stones[1]-stones[0]\n jump=stones[0]\n for i in range(len(stones)-2):\n jump=max(jump,stones[i+2]-stones[i])\n return jump\n\n``` | 1 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** o... | null |
[C++|Java|Python3] every other stone | frog-jump-ii | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/661cb4686dc915189ddbf0bc35fa51f408bf42ef) for solutions of biweekly 93. \n\n**Intuition**\nThe maximum distance of every other stone is the answer with an edge of `stones[1]` when there are only two stones. \n**Implementation**\n**C++**\n```\nclass... | 1 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** o... | null |
Python code | frog-jump-ii | 0 | 1 | # Code\n```\nclass Solution:\n def maxJump(self, stones: List[int]) -> int:\n l = len(stones)\n if l==3: return stones[2]\n answer = stones[1]\n for i in range(2, l, 2):\n if answer<stones[i]-stones[i-2]:answer=stones[i]-stones[i-2]\n for i in range(3, l, 2):\n ... | 1 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** o... | null |
Greedy solution with example and proof | frog-jump-ii | 0 | 1 | \n# Keypoint\n1. Use all rocks: the more rock in path, the better. This is because more rocks make each jump shorter.\n2. Jump alternatively is optimal. so we check all (stones[i+2] - stones[i]) and find maximum. \n\n# Proof\nWe use example `[1,2,3,4]` to prove alterntive-jump is optimal when n == 4. \n\nCase1: If frog... | 1 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** o... | null |
Decently explained Python3 code O(n) w/ Image | frog-jump-ii | 1 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nNo matter how you try, the best approach is always going to be skipping the next stone and going to next stone after that (if this step is possible). \n\nAfter drawing all possibilities it can be seen that the biggest steps are always going to be skip... | 20 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** o... | null |
Python O(n) solution | frog-jump-ii | 0 | 1 | # Approach\n- Finding difference between even position and odd position(from last)\n- Appending them into a list\n- Returning max value of list\n\n# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maxJump(self, st... | 2 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** o... | null |
Python 3 || 5 lines || T/M: 97% / 68% | frog-jump-ii | 0 | 1 | You can figure it out. I\'m pretty sure.\n\n"The secret of being a bore is to tell everything." \u2014 Voltaire\n\n```\nclass Solution:\n def maxJump(self, stones: List[int]) -> int:\n\n n = len(stones)\n\n ans = stones[1]\n\n for i in range(n-2):\n ans = max(ans,stones[i+2]-stones[i]... | 4 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** o... | null |
Python - Greedy O(n) - Video Solution | frog-jump-ii | 0 | 1 | The complete intuition is explained in this [video](https://www.youtube.com/watch?v=7eqGntQ7-Fs).\n\n# Intuition\nThe intution is, we have 3 stones `0, 10, 30`, \nthen we have to cover atleast `0 -> 30` / `30 -> 0 ` once.\n\nSo this max gap will be our answer.\n\nSo we try to find max distance between alternate stones... | 1 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** o... | null |
Python3 | Binary Search Solution | frog-jump-ii | 0 | 1 | \n# Code\n```\nclass Solution:\n def maxJump(self, stones: List[int]) -> int:\n l = 0;r = stones[-1]\n while l<r:\n m = (l+r)//2\n if valid(m,stones):\n r = m\n else:\n l = m+1\n return r\n\n\n\ndef valid(x,stones):\n i = 0;j = 0;n... | 1 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** o... | null |
One-liner - Python greedy solution O(n) | frog-jump-ii | 0 | 1 | # Intuition\nIf we use a stone, we cannot use it on our way back so we will have to jump above it, so we just need to look at the maximum gaps betwteen stones separated by one stone.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def maxJump(self, stones: Lis... | 2 | You are given a **0-indexed** integer array `stones` sorted in **strictly increasing order** representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone **at most once**.
The **length** o... | null |
Greedy || Python 3 | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | # Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n O(n)\n# Code\n```\nclass Solution:\n def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n n=len(nums1)\n ... | 1 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such... | null |
[Python 3] As Simple as Possible | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | # Intuition\n* `ans` $\\ge$ sum of bad indices\n* it\'s "efficient" to make pairs of bad indices and swap them with each other whenever possible\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def minimumTotalCost(self, nums1: List[int], nums2: List[int]... | 1 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such... | null |
[C++||Java||Python] O(1) space complexity with Moore vote algorithm | minimum-total-cost-to-make-arrays-unequal | 1 | 1 | > **I know almost nothing about English, pointing out the mistakes in my article would be much appreciated.**\n\n> **In addition, I\'m too weak, please be critical of my ideas.**\n\n> **Vote welcome if this solution helped.**\n---\n# Intuition\n\n1. Define "internally" as indexes $i$ satisfy $$a[i] = b[i]$$. It seems t... | 3 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such... | null |
[Python] Detailed explanation, readable code | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | This is not my invention. I borrowed this solution from [@bucketpotato](https://leetcode.com/bucketpotato/), analyzed it and made a super detailed version of their code.\n\n```python\nclass Solution:\n def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n inputLength = len(nums1)\n maxNumber =... | 4 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such... | null |
Algorithm specific to this problem | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nClearly, the minimum cost includes the sum of all i for which nums1[i]=nums2[i].\n\nIn certain circumstances, this is the actual answer. However, there are two cases when this may not be true:\n- when the number of such indices is odd\n- ... | 7 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such... | null |
[Python] Find smallest set to permute | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | ### Approach\nBecause swapping to and from index $0$ is free, if $S\'$ is the set of indices that are in at least one swap in the answer, then the optimal cost is `sum(S\')`.\n\nLet $S \\subseteq S\'$ be the set of $i$ with $A[i] = B[i]$. We have to move these, so the answer is at least `sum(S)`. Note that if all $A[... | 8 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such... | null |
Frequency Transform | Commented and Explained | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrequency transform of the problem space makes this much easier, since we can consider the costs based around the most frequent value in the arrays and the frequency of matches in the arrays. \n\nOnce we know the frequency of matches, and... | 0 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such... | null |
Python 3 | Solution | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | # Code\n```\nclass Solution:\n def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n \n matched = defaultdict(int)\n unmatched = defaultdict(list)\n\n res = 0\n for i, (x,y) in enumerate(zip(nums1, nums2)):\n if x == y:\n res += i\n ... | 0 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such... | null |
Python Solution | minimum-total-cost-to-make-arrays-unequal | 1 | 1 | \tclass Solution:\n\t\tdef minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n\t\t\td = Counter(nums2)\n\t\t\tn = len(nums1)\n\t\t\th = n//2\n\t\t\tfor i,j in d.items():\n\t\t\t\tif j>h:\n\t\t\t\t\treturn -1\n\t\t\td = defaultdict(int)\n\t\t\tans = 0\n\t\t\tcnt =0\n\t\t\tfor i in range(n):\n\t\t\t\tif ... | 0 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such... | null |
[Python3] | Greedy | Steps Explained. | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | 1. Store all indexes in arr which have equal element in nums1 and nums2.\n2. If max Freq element in arr is less than or equal to len(arr) then element can interchange among themselves -> return sum(arr)\n3. if max Freq element in arr is greater than len(arr) , then we need to add some indexes , so that freq will become... | 0 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such... | null |
Python | Clean Code | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | \n# Code\n```\nfrom collections import Counter\nclass Solution:\n def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n n = len(nums1)\n res = 0\n d = Counter()\n t = 0\n most = 0\n v = None\n for i,(x,y) in enumerate(zip(nums1, nums2)):\n ... | 0 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such... | null |
Python Linear time Linear Space Solution | minimum-total-cost-to-make-arrays-unequal | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n sz, ctr = len(nums... | 0 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such... | null |
Python Solution with Explanation - 2 codes where Leetcode testcases running fine but mine Fails | minimum-total-cost-to-make-arrays-unequal | 1 | 1 | \tclass Solution:\n\t\tdef minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n\t\t\t#this is the which accepted but can fail for some cases if leetcode did something good otherwise always will be ac.\n\t\t\t"""\n\t\t\td = Counter(nums2)\n\t\t\tn = len(nums1)\n\t\t\th = n//2\n\t\t\tfor i,j in d.items():... | 0 | You are given two **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such... | null |
Python (Simple Hashmap + Maths) | minimum-total-cost-to-make-arrays-unequal | 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 **0-indexed** integer arrays `nums1` and `nums2`, of equal length `n`.
In one operation, you can swap the values of any two indices of `nums1`. The **cost** of this operation is the **sum** of the indices.
Find the **minimum** total cost of performing the given operation **any** number of times such... | null |
✅✅Simple Python Solution 100% Faster || Easy Solution ✅✅ | delete-greatest-value-in-each-row | 0 | 1 | # Code\n```\nclass Solution:\n def deleteGreatestValue(self, grid: List[List[int]]) -> int:\n for i in range(0, len(grid)):\n grid[i].sort()\n n = len(grid[0])\n res = 0\n for j in range(0, n):\n ans = 0\n for i in range(0, len(grid)):\n ans... | 1 | You are given an `m x n` matrix `grid` consisting of positive integers.
Perform the following operation until `grid` becomes empty:
* Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them.
* Add the maximum of deleted elements to the answer.
**Note** that t... | null |
Sort Rows | delete-greatest-value-in-each-row | 0 | 1 | We sort all rows first, then go column by column and pick the largest value.\n\n**Python 3**\n```python\nclass Solution:\n def deleteGreatestValue(self, grid: List[List[int]]) -> int:\n return sum(max(c) for c in zip(*[sorted(r) for r in grid]))\n```\n\n**C++**\n```cpp\nint deleteGreatestValue(vector<vector<i... | 39 | You are given an `m x n` matrix `grid` consisting of positive integers.
Perform the following operation until `grid` becomes empty:
* Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them.
* Add the maximum of deleted elements to the answer.
**Note** that t... | null |
Python || Beats 79 % || Easy | delete-greatest-value-in-each-row | 0 | 1 | # Code\n```\nclass Solution:\n def deleteGreatestValue(self, grid: List[List[int]]) -> int:\n \n res = 0\n \n n = len(grid[0])\n \n for i in range(n):\n maxi = 0\n for j in grid:\n new = max(j)\n maxi = max(maxi,new)\n ... | 1 | You are given an `m x n` matrix `grid` consisting of positive integers.
Perform the following operation until `grid` becomes empty:
* Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them.
* Add the maximum of deleted elements to the answer.
**Note** that t... | null |
Python | Easy Solution✅ | delete-greatest-value-in-each-row | 0 | 1 | # Code\u2705\n```\nclass Solution:\n def deleteGreatestValue(self, grid: List[List[int]]) -> int:\n i = 0\n output = 0\n current_max = 0\n while True:\n if len(grid[i]) == 0:\n break\n grid[i] = sorted(grid[i])\n current_max = max(current_ma... | 6 | You are given an `m x n` matrix `grid` consisting of positive integers.
Perform the following operation until `grid` becomes empty:
* Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them.
* Add the maximum of deleted elements to the answer.
**Note** that t... | null |
[C++|Java|Python3] sorting | delete-greatest-value-in-each-row | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/8f409c5e220a4a1a1d7fdfbfcc1dcd24eeead232) for solutions of weekly 323. \n\n**Intuition**\nThe problem can be solved by sorting each row and sum the largest of each column. \n**Implementation**\n**C++**\n```\nclass Solution {\npublic:\n int delet... | 2 | You are given an `m x n` matrix `grid` consisting of positive integers.
Perform the following operation until `grid` becomes empty:
* Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them.
* Add the maximum of deleted elements to the answer.
**Note** that t... | null |
Recursive Solution for Python | delete-greatest-value-in-each-row | 0 | 1 | # Code\n```\nclass Solution:\n def deleteGreatestValue(self, grid: List[List[int]]) -> int:\n return self.calculate_answer(grid, 0)\n\n def calculate_answer(self, grid: List[List[int]], answer: int) -> int:\n if grid[0] == []:\n return answer\n\n current_max = 0\n for i in g... | 1 | You are given an `m x n` matrix `grid` consisting of positive integers.
Perform the following operation until `grid` becomes empty:
* Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them.
* Add the maximum of deleted elements to the answer.
**Note** that t... | null |
Python 3 || 3 lines, w/ explanation and example || T/M: 102 ms / 14MB | delete-greatest-value-in-each-row | 0 | 1 | ```\nclass Solution:\n def deleteGreatestValue(self, grid: List[List[int]]) -> int:\n\n for i in range(len(grid)): grid[i].sort() # <-- sort each row\n\n grid = list(zip(*grid)) # <-- transpose grid; rows become\n # cols and c... | 11 | You are given an `m x n` matrix `grid` consisting of positive integers.
Perform the following operation until `grid` becomes empty:
* Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them.
* Add the maximum of deleted elements to the answer.
**Note** that t... | null |
[Python / JS] dont use expensive sqrt() function | longest-square-streak-in-an-array | 0 | 1 | # Python\n```\nclass Solution:\n def longestSquareStreak(self, nums: List[int]) -> int:\n nums.sort(reverse=True)\n seen = {}\n ans = -1\n\n for n in nums:\n if n*n in seen:\n seen[n] = seen[n*n]+1\n ans = max(ans, seen[n])\n else:\n ... | 1 | You are given an integer array `nums`. A subsequence of `nums` is called a **square streak** if:
* The length of the subsequence is at least `2`, and
* **after** sorting the subsequence, each element (except the first element) is the **square** of the previous number.
Return _the length of the **longest square st... | null |
Python | Optimal O(n) | easy to understand | longest-square-streak-in-an-array | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def longestSquareStreak(self, nums: List[int]) -> int:\n nums.sort()\n d = {}\n ans = 0\n for i, n in enumerate(nums):\n sqrt = n ** 0.5\n if sqrt in d and sqrt.is_integer():\n d[n] = d[sqrt] + 1\n ans ... | 1 | You are given an integer array `nums`. A subsequence of `nums` is called a **square streak** if:
* The length of the subsequence is at least `2`, and
* **after** sorting the subsequence, each element (except the first element) is the **square** of the previous number.
Return _the length of the **longest square st... | null |
Python 3 || 11 lines, mathematics, w/ brief comments || T/M: 97%/68% | longest-square-streak-in-an-array | 0 | 1 | Pretty much the same solution as others, except the set of potential squares has been pruned back to just those numbers `n` such that `n%4 == 0` or `n%4 == 1`. \n```\nclass Solution:\n def longestSquareStreak(self, nums: List[int]) -> int:\n\n s = set(nums)\n nums, ans = sorted(s), 0\n s = {n f... | 4 | You are given an integer array `nums`. A subsequence of `nums` is called a **square streak** if:
* The length of the subsequence is at least `2`, and
* **after** sorting the subsequence, each element (except the first element) is the **square** of the previous number.
Return _the length of the **longest square st... | null |
6 lines with hashmap | longest-square-streak-in-an-array | 0 | 1 | reversing nums is better because no need to take care of float\n\n# Code\n```\nclass Solution:\n def longestSquareStreak(self, nums: List[int]) -> int:\n ans, buf = -1, {}\n for n in reversed(sorted(nums)):\n buf[n] = buf.get(n*n, 0) + 1\n if buf[n] > 1:\n ans = max... | 3 | You are given an integer array `nums`. A subsequence of `nums` is called a **square streak** if:
* The length of the subsequence is at least `2`, and
* **after** sorting the subsequence, each element (except the first element) is the **square** of the previous number.
Return _the length of the **longest square st... | null |
[Python 3] Simple | Using set | longest-square-streak-in-an-array | 0 | 1 | ```\nclass Solution:\n def longestSquareStreak(self, nums: List[int]) -> int:\n uniq = set(nums)\n res = 0\n \n for i in nums:\n temp = i\n t = 0\n while temp * temp in uniq:\n temp *= temp\n t += 1\n \n ... | 2 | You are given an integer array `nums`. A subsequence of `nums` is called a **square streak** if:
* The length of the subsequence is at least `2`, and
* **after** sorting the subsequence, each element (except the first element) is the **square** of the previous number.
Return _the length of the **longest square st... | null |
✔ Python3 Solution | DP | Clean & Concise | longest-square-streak-in-an-array | 0 | 1 | # Complexity\n- Time complexity: $$O(nlogn)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def longestSquareStreak(self, A):\n A.sort()\n n = len(A)\n dp = [1] * n\n r = n - 1\n for i in range(n - 1, -1, -1):\n while A[i] * A[i] < A[r]: r -= 1\n ... | 1 | You are given an integer array `nums`. A subsequence of `nums` is called a **square streak** if:
* The length of the subsequence is at least `2`, and
* **after** sorting the subsequence, each element (except the first element) is the **square** of the previous number.
Return _the length of the **longest square st... | null |
[C++|Java|Python3] dp | longest-square-streak-in-an-array | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/8f409c5e220a4a1a1d7fdfbfcc1dcd24eeead232) for solutions of weekly 323. \n\n**Intuition**\nIt is quite strange that sorting is allowed in this problem. However, since sorting is allowed, all that matters is whether a squared number exists. One solut... | 2 | You are given an integer array `nums`. A subsequence of `nums` is called a **square streak** if:
* The length of the subsequence is at least `2`, and
* **after** sorting the subsequence, each element (except the first element) is the **square** of the previous number.
Return _the length of the **longest square st... | null |
[C++|Java|Python3] brute-force | design-memory-allocator | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/8f409c5e220a4a1a1d7fdfbfcc1dcd24eeead232) for solutions of weekly 323. \n\n**Intuition**\nThis is a brute-force solution where in `allocate` I traverse the whole `memory` array to find the consecutive free block of given size and in `free` I also t... | 1 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the g... | null |
Beats 100% solutions | design-memory-allocator | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the g... | null |
✅✅Simplest Python Solution Without HashMap✅✅ | design-memory-allocator | 0 | 1 | # Code\n```\nclass Allocator:\n\n def __init__(self, n: int):\n self.mem = [0]*n\n \n def allocate(self, size: int, mID: int) -> int:\n def checksize(size):\n flag = False \n pos = -1\n count = 0\n for i in range(0, len(self.mem)):\n ... | 1 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the g... | null |
Python simple solution with video explanation | design-memory-allocator | 0 | 1 | # Approach\ncreate an array of length n initialize with -1 \n- for allocate look for a free block of length size, once found set all values in it to mID and returns the start index \n- for free find all those set to mID and set to -1 \n\nVideo explanation: https://www.youtube.com/watch?v=k9l1PvIRNRw\n# Code\n```\nclass... | 8 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the g... | null |
[Python 3] First Fit | design-memory-allocator | 0 | 1 | ```\nclass Allocator:\n\n def __init__(self, n: int):\n self.nums = [0] * n\n \n\n def allocate(self, size: int, mID: int) -> int:\n if size > len(self.nums): return -1\n \n\t\t# availableBlocks is to calculate size of available memory blocks and their starting index.\n availab... | 1 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the g... | null |
Python 3 || Brute Force | design-memory-allocator | 0 | 1 | # Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n O(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n O(n)\n# Code\n```\nclass Allocator:\n\n def __init__(self, n: int):\n self.arr=[0 for i in range(n)]\n self.n=n\n\n... | 2 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the g... | null |
Python- Abuse strings to beat 97% in O(n) | design-memory-allocator | 0 | 1 | # Approach\nEncode the whole thing as a unicode string, where the free blocks and non-free blocks have identities as characters. Then use the string api to implement behavior.\n\n# Complexity\n- Time complexity:\n$O(n)$, but very nice constant factor\n\n- Space complexity:\n$O(n)$\n\n\n# Code\n```\nFREE = chr(0)\n\ncla... | 3 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the g... | null |
Real allocator that beats 100% | design-memory-allocator | 0 | 1 | # Intuition\n1. Use a linked list to track all memory blocks. It starts with a single block for all the available memory\n2. Use a dict to track all allocations\n\nIf you like my implementation please upvote!\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Allocator:\n cl... | 2 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the g... | null |
Python Solution | HashMap and List | Easy to Understand | design-memory-allocator | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n1) <b>Constructor</b>\n For memory allocation, We use a list i.e. ```self.memory``` and to store indices of allocated memory to ```mID```, We use hashmap i.e. ```self.hashMap``` which stores ```mID``` and all indices allocated to it.\n\n2) <b>Alloc... | 2 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the g... | null |
python3 beats 98% | design-memory-allocator | 0 | 1 | \nApproach: merge the list of blocks to be freed with the freelist in one pass. This requires list of blocks to be freed to be sorted by offset.\n(if there adjacent blocks in list of blocks to be freed, then combine them before freeing them)\n\n# Code\n```\n\nclass Entry:\n def __init__(self, offset, size, mid):\n ... | 0 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the g... | null |
beats 100 % easy solution | design-memory-allocator | 0 | 1 | # Intuition\n\nThis is similar to non-overlaping ranges solution. if you have solved those problems, you will find this easy too.\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWe make a list where we store ranges of memory allocated in sorted manned. This way we can find any memo... | 0 | You are given an integer `n` representing the size of a **0-indexed** memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
1. **Allocate** a block of `size` consecutive free memory units and assign it the id `mID`.
2. **Free** all memory units with the g... | null |
🤯 [Python] Simplest solution | Detailed explanation | BFS + Heap | Codeplug | maximum-number-of-points-from-grid-queries | 0 | 1 | # Intuition\nWe need to traverse to the furthest possible distance from 0,0 for any given query. A BFS can help here, but normal BFS means we explore all possible neighbours, can we improve it by greedily selecting the smallest neighbour first?\n\nAnd as soon as we reach a neighbour thats >= query, we can stop the trav... | 4 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cel... | null |
Python solution: priority queue and then binary search | maximum-number-of-points-from-grid-queries | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe want to find the threshold to gain a point at each coordinate\nThe answer is the maximum between grid[i][j] and the minimum of thresholds of its neighbours\n\nTherefore I figured I should not be doing BFS, but should use a priority que... | 3 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cel... | null |
Intuitive Python BFS with Heap explained + complexity | maximum-number-of-points-from-grid-queries | 0 | 1 | Inuition:\n\n* Iterate through the queries from smallest to largest.\n* BFS, starting from top-left. Only visit cells that are smaller than the current query.\n * Once we visit a cell, then we will consider the neighbors.\n * Priority queue / min-heap helps us do this efficiently. Priority is based on value of th... | 1 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cel... | null |
Python BFS + Min Heap Solution, Faster than 100% | maximum-number-of-points-from-grid-queries | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can sort queries. Just remember to return the results in the original order. Given a threshold ```query```, we can form a reachable region from (0,0), and we can record the boundary. This can be done by BFS with min heap. Given a larger threshold... | 1 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cel... | null |
[Python3] BFS + heap + prefixsum | maximum-number-of-points-from-grid-queries | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nKeep visiting smallest nodes as you see them. Keep running maximum and store that track that maximum number -> nodes seen. Take the keys and values out of the array and sort by key. Calculate prefix sum of the values. For each query, pe... | 1 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cel... | null |
Python3 Djikstra Priority Queue | maximum-number-of-points-from-grid-queries | 0 | 1 | Run dijkstra through the matrix. Update the maximum number you\'ve reached as you go along and keep your results in a dictionary. \n-->Your dictionary should keep track of the maximum number of cells each number can reach\nFor each query, find the maximum in your dictionary that you can reach. Could binary search this ... | 1 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cel... | null |
[Python] with explanation, dynamic programming, dfs, heap | maximum-number-of-points-from-grid-queries | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthe bigger query will cover all nodes traversed by the smaller queries.\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. sort the query array and keep track of its original index to solve the problem with dyn... | 1 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cel... | null |
[C++|Python3] priority queue + binary search | maximum-number-of-points-from-grid-queries | 0 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/8f409c5e220a4a1a1d7fdfbfcc1dcd24eeead232) for solutions of weekly 323. \n\n**Intuition**\nHere I traverse the grid from the top-left cell. In the meantime, I use a priority queue to keep track of the largest value required to reach a cell. A separa... | 11 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cel... | null |
Python 3 Solution with Explanation - Heap + Binary Search + BFS | maximum-number-of-points-from-grid-queries | 1 | 1 | **Explanation**\nIt is an graph based question we just have to get the full path from the top left (0,0).\nAnd after that we have to just do a simple binary search (bisect_left or lower_bound) in the *order*\nto get the result.\n\n\n\n\n\n\n\n\tclass Solution:\n\t\tdef maxPoints(self, grid: List[List[int]], queries: Li... | 26 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cel... | null |
[Python] EVERY DETAIL Documented | Short Elegant Heap Solution | maximum-number-of-points-from-grid-queries | 0 | 1 | # Raw Answer (Documented code below)\n\n```\nclass Solution(object):\n def maxPoints(self, grid, queries):\n """\n Original answer: https://leetcode.com/problems/maximum-number-of-points-from-grid-queries/solutions/2899594/python-3-solution-with-explanation-heap-binary-search/\n """\n \n ... | 2 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cel... | null |
Python - Heap + Binary Search - Video Solution | maximum-number-of-points-from-grid-queries | 0 | 1 | I have explained the solution in this [video](https://youtu.be/zZWSZM7fboI).\n\n**Time**: `O( mn. log(mn) + k. log(mn))`\n\n**Space**: `O(mn)`\n\nIf this was helpful, please **Upvote**, like the video and subscribe to the channel.\n\n\n```\nclass Solution:\n def maxPoints(self, grid: List[List[int]], queries: List[i... | 4 | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cel... | null |
Python |Binary search | Prioritise BFS | maximum-number-of-points-from-grid-queries | 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` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cel... | null |
Count Pairs Of Similar Strings | count-pairs-of-similar-strings | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the ... | null |
[Python] symmetric difference of two Set, Explained. | count-pairs-of-similar-strings | 0 | 1 | We get the character set for each word, and then, we just need to check the difference between any pair of two character sets.\n\nThe python set method: `symmetric_difference` can do the job.\n\n```\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n wd_set = collections.defaultdict(set)\n ... | 1 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the ... | null |
CodeDominar Solution | count-pairs-of-similar-strings | 0 | 1 | # Code\n```\n@1st approach \n\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n d=Counter()\n count=0\n for current_word in words:\n word="".join(sorted(set(current_word)))\n count+=d[word]\n d[word]+=1\n return count \n##############... | 1 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the ... | null |
[Python 3] Dictionary key is tuple of sorted set || beats 100% || 51ms 🥷🏼 | count-pairs-of-similar-strings | 0 | 1 | ```python3 []\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n d = defaultdict(int)\n for n in words:\n d[tuple(sorted(set(n)))] += 1\n\n return sum(v * (v-1) // 2 for v in d.values())\n```\n space, O(n*k) Time || Hashmap approach [Python3] | count-pairs-of-similar-strings | 0 | 1 | Bear with me, answer isn\'t hard at all\njust follow the intuition\n> Please Leave a like if you liked the approach\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAnalyzing the input array `words` and the problem description `Two strings are similar if they consist of the same char... | 42 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the ... | null |
[C++|Java|Python3] frequency table + mask | count-pairs-of-similar-strings | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/af6e415cd101768ea8743ea9e4d22d788c9461c3) for solutions of weekly 324. \n\n**Intuition**\nHere, we can use a mask to indicate what characters appear in a word, and use a hash table to indicate the frequency of a mask. \n**Implementation**\n**C++**\... | 52 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the ... | null |
Python Easy to Understand code || Accepted✅ | count-pairs-of-similar-strings | 0 | 1 | # Approach\nusing sets to check if two words in the array words contain same characters. \n\n# Complexity\n- Time complexity:\nsince a nested for is used, O(n^2)\n\n# Code\n```\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n count = 0\n for i in range(len(words)):\n for... | 2 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the ... | null |
Python 3 || 1-5 lines, tuple and Counter , w/ explanation || T/M: 61 ms / 13.9 MB | count-pairs-of-similar-strings | 0 | 1 | ```\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n\n words = [set (w) for w in words] # <\u2013\u2013 map each word to its letter-set\n words = [sorted(w) for w in words] # <\u2013\u2013 map each letter-set to its sorted list\n words = [tuple (w) for w ... | 5 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the ... | null |
Python3 Simple Hash Map Solution | count-pairs-of-similar-strings | 0 | 1 | \n# Approach\n1. We can hash the word as its unique characters sorted i.e `bacddd == abcd`.\n2. Now loop through the words updating the counts of each word type to find the amount of similar words. \n3. To find how many pairs there are we use the $$nC_2$$ formula which is simplified as $$\\frac{n*(n-1)}{2}$$\n\n# Code\... | 1 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the ... | null |
Python 3 count distinct pairs and adding into count variable | count-pairs-of-similar-strings | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the ... | null |
Python | Easy Solution✅ | count-pairs-of-similar-strings | 0 | 1 | # Code\u2705\n```\nclass Solution:\n def similarPairs(self, words: List[str]) -> int:\n count = 0\n for i in range(len(words)):\n for j in range(i):\n if set(words[i]) == set(words[j]):\n count +=1\n return count\n\n``` | 6 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the ... | null |
Python Accepted ✅ | count-pairs-of-similar-strings | 0 | 1 | ```\nclass Solution:\n def similarPairs(self, w: List[str]) -> int:\n cnt=0\n for i in range(len(w)):\n for j in range(i):\n # print(i,j)\n if set(w[i])==set(w[j]):\n cnt+=1\n return cnt\n \n``` | 10 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the ... | null |
Simple python solution using Brute-Force | count-pairs-of-similar-strings | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You are given a **0-indexed** string array `words`.
Two strings are **similar** if they consist of the same characters.
* For example, `"abca "` and `"cba "` are similar since both consist of characters `'a'`, `'b'`, and `'c'`.
* However, `"abacba "` and `"bcfd "` are not similar since they do not consist of the ... | null |
Python 3 || 10 lines, recursion, w/ brief explanation || T/M: 128 ms / 13.8MB | smallest-value-after-replacing-with-sum-of-prime-factors | 0 | 1 | ```\nclass Solution:\n def smallestValue(self, n):\n\n prev, ans = n, 0\n\n while not n%2: # 2 is the unique even prime\n ans += 2\n n//= 2\n\n for i in range(3,n+1,2): # <\u2013\u2013 prune even divisors...\n while not n%i:\n... | 3 | You are given a positive integer `n`.
Continuously replace `n` with the sum of its **prime factors**.
* Note that if a prime factor divides `n` multiple times, it should be included in the sum as many times as it divides `n`.
Return _the smallest value_ `n` _will take on._
**Example 1:**
**Input:** n = 15
**Outp... | null |
Python3 | Finding prime factors | Intuitive | Easy to understand | smallest-value-after-replacing-with-sum-of-prime-factors | 0 | 1 | \n# Code\n```\nclass Solution:\n def prime_factors(self, n):\n i = 2\n factors = []\n while i * i <= n:\n if n % i:\n i += 1\n else:\n n //= i\n factors.append(i)\n if n > 1:\n factors.append(n)\n return ... | 2 | You are given a positive integer `n`.
Continuously replace `n` with the sum of its **prime factors**.
* Note that if a prime factor divides `n` multiple times, it should be included in the sum as many times as it divides `n`.
Return _the smallest value_ `n` _will take on._
**Example 1:**
**Input:** n = 15
**Outp... | null |
SIMPLE PYTHON SOLUTION | smallest-value-after-replacing-with-sum-of-prime-factors | 0 | 1 | # Intuition\nMy intuition is that if I encounter any prime number in the process then that is the minimum of till now will be the answer or if we come across same number twice then we will return the minimum value.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity... | 1 | You are given a positive integer `n`.
Continuously replace `n` with the sum of its **prime factors**.
* Note that if a prime factor divides `n` multiple times, it should be included in the sum as many times as it divides `n`.
Return _the smallest value_ `n` _will take on._
**Example 1:**
**Input:** n = 15
**Outp... | null |
Easy python solution | smallest-value-after-replacing-with-sum-of-prime-factors | 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 ---> 61 ms\n- Space complexity:\n<!-- Add your space complexity here, e.g... | 1 | You are given a positive integer `n`.
Continuously replace `n` with the sum of its **prime factors**.
* Note that if a prime factor divides `n` multiple times, it should be included in the sum as many times as it divides `n`.
Return _the smallest value_ `n` _will take on._
**Example 1:**
**Input:** n = 15
**Outp... | null |
CodeDominar Solution | smallest-value-after-replacing-with-sum-of-prime-factors | 0 | 1 | # Code\n```\nclass Solution:\n def smallestValue(self, n: int) -> int:\n def find_factors_sum(n):\n sum_ = 0\n for i in range(2,n):\n while n%i==0:\n sum_+=i\n n = n//i\n return sum_\n while find_factors_sum(n) and n!... | 1 | You are given a positive integer `n`.
Continuously replace `n` with the sum of its **prime factors**.
* Note that if a prime factor divides `n` multiple times, it should be included in the sum as many times as it divides `n`.
Return _the smallest value_ `n` _will take on._
**Example 1:**
**Input:** n = 15
**Outp... | null |
[Python3] Enumerate all possible cases for 2 and 4 odd-degree nodes in the graph | add-edges-to-make-degrees-of-all-nodes-even | 0 | 1 | **Observation**\nThe key is to note that we can add **at most** two additional edges (possibly none) to the graph.\n\n**Implementation**\nStep 1: Build the graph by going through all edges.\nStep 2: Find every node with an odd degree.\nStep 3: Consider each of the case where the number of the nodes with an odd degree i... | 5 | There is an **undirected** graph consisting of `n` nodes numbered from `1` to `n`. You are given the integer `n` and a **2D** array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi`. The graph can be disconnected.
You can add **at most** two additional edges (possibly none... | null |
[C++|Java|Python3] 3 cases for true | add-edges-to-make-degrees-of-all-nodes-even | 1 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/af6e415cd101768ea8743ea9e4d22d788c9461c3) for solutions of weekly 324. \n\n**Intuition**\nThere are 3 cases where it is possible to get all even degrees with at most two more edges; \n1) The nodes already have all even degrees; \n2) There are two n... | 3 | There is an **undirected** graph consisting of `n` nodes numbered from `1` to `n`. You are given the integer `n` and a **2D** array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi`. The graph can be disconnected.
You can add **at most** two additional edges (possibly none... | null |
Case by case python solution | add-edges-to-make-degrees-of-all-nodes-even | 0 | 1 | # Intuition\nProblem is only solvable if odd nodes are 2 or 4. Note that it is impossible for there to be 1 or 3 odd nodes, since sum(degrees) %2 == 0\n\n# Approach\nWith 2 odds, they can either connect to each other or to some other vertex that neither is connected to\n\nWith 4 odds, there must be two separate pairs o... | 1 | There is an **undirected** graph consisting of `n` nodes numbered from `1` to `n`. You are given the integer `n` and a **2D** array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi`. The graph can be disconnected.
You can add **at most** two additional edges (possibly none... | null |
HRT CodeSignal test problem | add-edges-to-make-degrees-of-all-nodes-even | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI actually encountered this problem on HRT online OA\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThere are only 3 cases to return true:\n1. All nodes are even\n2. 2 nodes are odd, find a free node or between them... | 1 | There is an **undirected** graph consisting of `n` nodes numbered from `1` to `n`. You are given the integer `n` and a **2D** array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi`. The graph can be disconnected.
You can add **at most** two additional edges (possibly none... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.