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 |
|---|---|---|---|---|---|---|---|
python3 Solution | maximize-win-from-two-segments | 0 | 1 | \n```\nclass Solution:\n def maximizeWin(self, prizePositions: List[int], k: int) -> int:\n dp=[0]*(len(prizePositions)+1)\n res=0\n j=0\n for i,a in enumerate(prizePositions):\n while prizePositions[j]<prizePositions[i]-k:\n j+=1\n dp[i+1]=max(dp[i],i... | 3 | There are some prizes on the **X-axis**. You are given an integer array `prizePositions` that is **sorted in non-decreasing order**, where `prizePositions[i]` is the position of the `ith` prize. There could be different prizes at the same position on the line. You are also given an integer `k`.
You are allowed to sele... | null |
Python Solution Using Binary Search | maximize-win-from-two-segments | 0 | 1 | # Code\n```\nfrom bisect import bisect_right,bisect_left\nclass Solution:\n def maximizeWin(self, prizePositions: List[int], k: int) -> int:\n ans=prv=0\n for i,item in enumerate(prizePositions):\n j1=bisect_left(prizePositions,item-k)\n j2=bisect_right(prizePositions,item+k)\n ... | 2 | There are some prizes on the **X-axis**. You are given an integer array `prizePositions` that is **sorted in non-decreasing order**, where `prizePositions[i]` is the position of the `ith` prize. There could be different prizes at the same position on the line. You are also given an integer `k`.
You are allowed to sele... | null |
maximize win from two segments | maximize-win-from-two-segments | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | There are some prizes on the **X-axis**. You are given an integer array `prizePositions` that is **sorted in non-decreasing order**, where `prizePositions[i]` is the position of the `ith` prize. There could be different prizes at the same position on the line. You are also given an integer `k`.
You are allowed to sele... | null |
Python Medium | maximize-win-from-two-segments | 0 | 1 | ```\nclass Solution:\n def maximizeWin(self, prizePositions: List[int], k: int) -> int:\n\n N = len(prizePositions)\n\n dp = [0] * (N + 1)\n\n l = 0\n\n ans = 0\n\n for r in range(N):\n\n while prizePositions[l] + k < prizePositions[r]:\n l += 1\n\n ... | 0 | There are some prizes on the **X-axis**. You are given an integer array `prizePositions` that is **sorted in non-decreasing order**, where `prizePositions[i]` is the position of the `ith` prize. There could be different prizes at the same position on the line. You are also given an integer `k`.
You are allowed to sele... | null |
Python Sliding Window O(N). Clean Code + Intuition + Similar problem | maximize-win-from-two-segments | 0 | 1 | # Intuition\nThis is the same problem as:\nhttps://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/editorial, Approach 1: Bidirectional Dynamic Programming, where you want a max to the left of i and a max to the right of i.\n\n# Approach\n1. Use a counter to get a num -> count mapping so the distance to itera... | 0 | There are some prizes on the **X-axis**. You are given an integer array `prizePositions` that is **sorted in non-decreasing order**, where `prizePositions[i]` is the position of the `ith` prize. There could be different prizes at the same position on the line. You are also given an integer `k`.
You are allowed to sele... | null |
Python3 Dynamic programming | maximize-win-from-two-segments | 0 | 1 | # Approach\n- Need to choose at most two segment, the dfs function should go through all index or run out of two segments.\n- There are two states in each index, pick or not pick\n- If pick the idx, skip the value less or equal than the value plus k. \n ex: `prize[idx] = 1 and k = 2`\n It can cover from value 1 t... | 0 | There are some prizes on the **X-axis**. You are given an integer array `prizePositions` that is **sorted in non-decreasing order**, where `prizePositions[i]` is the position of the `ith` prize. There could be different prizes at the same position on the line. You are also given an integer `k`.
You are allowed to sele... | null |
Use two points cleverly | maximize-win-from-two-segments | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | There are some prizes on the **X-axis**. You are given an integer array `prizePositions` that is **sorted in non-decreasing order**, where `prizePositions[i]` is the position of the `ith` prize. There could be different prizes at the same position on the line. You are also given an integer `k`.
You are allowed to sele... | null |
Python (Simple DP + Sliding Window) | maximize-win-from-two-segments | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | There are some prizes on the **X-axis**. You are given an integer array `prizePositions` that is **sorted in non-decreasing order**, where `prizePositions[i]` is the position of the `ith` prize. There could be different prizes at the same position on the line. You are also given an integer `k`.
You are allowed to sele... | null |
✅ Clever Diagonals with Diagram Explanation ✅ | disconnect-path-in-a-binary-matrix-by-at-most-one-flip | 0 | 1 | # Overview\n- The brute force solution would be to search the grid for every $$1$$ that can be flipped. However, this solution would lead to TLE. \n - Instead, we can do this problem in $$O(mn)$$. Precisely 3 iterations of the entire grid. \n - All we need is $$O(m+n)$$ extra space for a list of diagonals. \n- It... | 43 | You are given a **0-indexed** `m x n` **binary** matrix `grid`. You can move from a cell `(row, col)` to any of the cells `(row + 1, col)` or `(row, col + 1)` that has the value `1`. The matrix is **disconnected** if there is no path from `(0, 0)` to `(m - 1, n - 1)`.
You can flip the value of **at most one** (possibl... | null |
DP | Count number of path | Simple solution | disconnect-path-in-a-binary-matrix-by-at-most-one-flip | 0 | 1 | # Intuition\nIf there exist a point `(i, j)` which is not `(0, 0)` or `(m-1, n-1)`, such that the number of the paths from `(0, 0)` to `(m-1, n-1)` go through `(i, j)`equals the number of paths from `(0, 0)` to `(m-1, n-1)` without any constraint, return True.\n\n# Approach\n\nTo count the numbers of paths go through `... | 52 | You are given a **0-indexed** `m x n` **binary** matrix `grid`. You can move from a cell `(row, col)` to any of the cells `(row + 1, col)` or `(row, col + 1)` that has the value `1`. The matrix is **disconnected** if there is no path from `(0, 0)` to `(m - 1, n - 1)`.
You can flip the value of **at most one** (possibl... | null |
[Python🐍] Simple DFS - remember the path and remove the path | disconnect-path-in-a-binary-matrix-by-at-most-one-flip | 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\nGeneral approach is simple: 3 steps\n\n#1\ndo a DFS to reach the end (M-1,N-1) and remember the path.\n\n#2\nRemove the path by setting 0 all the way.\n\n#3\nTry DFS... | 17 | You are given a **0-indexed** `m x n` **binary** matrix `grid`. You can move from a cell `(row, col)` to any of the cells `(row + 1, col)` or `(row, col + 1)` that has the value `1`. The matrix is **disconnected** if there is no path from `(0, 0)` to `(m - 1, n - 1)`.
You can flip the value of **at most one** (possibl... | null |
[Python 3] DFS + BFS - Simple | disconnect-path-in-a-binary-matrix-by-at-most-one-flip | 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(M * N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(M * N)$$\n<!-- Add your space complex... | 3 | You are given a **0-indexed** `m x n` **binary** matrix `grid`. You can move from a cell `(row, col)` to any of the cells `(row + 1, col)` or `(row, col + 1)` that has the value `1`. The matrix is **disconnected** if there is no path from `(0, 0)` to `(m - 1, n - 1)`.
You can flip the value of **at most one** (possibl... | null |
【C++||Java||Python】DP and then count diagonals | disconnect-path-in-a-binary-matrix-by-at-most-one-flip | 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\n# Intuition\n1. Immediately it comes to mind that we have no reason to change $0$ to $1$.\n2. Note that only from left to right or fr... | 17 | You are given a **0-indexed** `m x n` **binary** matrix `grid`. You can move from a cell `(row, col)` to any of the cells `(row + 1, col)` or `(row, col + 1)` that has the value `1`. The matrix is **disconnected** if there is no path from `(0, 0)` to `(m - 1, n - 1)`.
You can flip the value of **at most one** (possibl... | null |
[Python] Diagonal Trick. Simple and intuitive solution. | disconnect-path-in-a-binary-matrix-by-at-most-one-flip | 0 | 1 | # Intuition\nNotice that every path has to go through one of the antidiagonals (those that go from the bottom left to the top right). So if we can block at least one of these diagonals, a.k.a. assign zeros to all of its elements, there won\'t be any path.\n\n# Approach\nCount the number of ones for each antidiagonal. T... | 1 | You are given a **0-indexed** `m x n` **binary** matrix `grid`. You can move from a cell `(row, col)` to any of the cells `(row + 1, col)` or `(row, col + 1)` that has the value `1`. The matrix is **disconnected** if there is no path from `(0, 0)` to `(m - 1, n - 1)`.
You can flip the value of **at most one** (possibl... | null |
DFS | Python3 | O(m*n) Time | O(1) Space | disconnect-path-in-a-binary-matrix-by-at-most-one-flip | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf we need to disconnect them then we just need to block the node which we visit. If still we can reach the end node more than once, then we can not disconnect them in a single flip.\n\n# Approach\n<!-- Describe your approach to solving t... | 5 | You are given a **0-indexed** `m x n` **binary** matrix `grid`. You can move from a cell `(row, col)` to any of the cells `(row + 1, col)` or `(row, col + 1)` that has the value `1`. The matrix is **disconnected** if there is no path from `(0, 0)` to `(m - 1, n - 1)`.
You can flip the value of **at most one** (possibl... | null |
Python 3 | Greedy, DFS | Explanation | disconnect-path-in-a-binary-matrix-by-at-most-one-flip | 0 | 1 | # Intuition\n- If there are two paths that \n - can reach from top-left to bottom-right\n - has no overlap (except starting & ending point)\n- Then, it\'s not possible to disconnect the graph with one flip\n\n# Approach\n- The intuition is straight forward, but how do we do that? \n - Find out all paths and co... | 2 | You are given a **0-indexed** `m x n` **binary** matrix `grid`. You can move from a cell `(row, col)` to any of the cells `(row + 1, col)` or `(row, col + 1)` that has the value `1`. The matrix is **disconnected** if there is no path from `(0, 0)` to `(m - 1, n - 1)`.
You can flip the value of **at most one** (possibl... | null |
Python DFS solution | Number of independent paths | Beats 96% | O(n*m) | O(1) | disconnect-path-in-a-binary-matrix-by-at-most-one-flip | 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** `m x n` **binary** matrix `grid`. You can move from a cell `(row, col)` to any of the cells `(row + 1, col)` or `(row, col + 1)` that has the value `1`. The matrix is **disconnected** if there is no path from `(0, 0)` to `(m - 1, n - 1)`.
You can flip the value of **at most one** (possibl... | null |
DFS For Two Paths | disconnect-path-in-a-binary-matrix-by-at-most-one-flip | 0 | 1 | # Approach\nWe can\'t make matrix disconnected in case when two independent paths from (0, 0) to (m-1, n-1) exist.\n\n# Complexity\n- Time complexity: $$O(m*n)$$.\n\n- Space complexity: $$O(m+n)$$.\n\n# Code\n```\nclass Solution:\n def isPossibleToCutPath(self, grid: List[List[int]]) -> bool:\n m, n = len(gri... | 0 | You are given a **0-indexed** `m x n` **binary** matrix `grid`. You can move from a cell `(row, col)` to any of the cells `(row + 1, col)` or `(row, col + 1)` that has the value `1`. The matrix is **disconnected** if there is no path from `(0, 0)` to `(m - 1, n - 1)`.
You can flip the value of **at most one** (possibl... | null |
Python | 100% Faster | Easy Solution✅ | take-gifts-from-the-richest-pile | 0 | 1 | # Code\u2705\n```\nimport math\nclass Solution:\n def pickGifts(self, gifts: List[int], k: int) -> int:\n i = 0\n while i < k:\n gifts = sorted(gifts)\n sqrt = math.floor(math.sqrt(gifts[-1]))\n gifts[-1] = sqrt\n i +=1\n return sum(gifts)\n```\n![Scre... | 9 | You are given an integer array `gifts` denoting the number of gifts in various piles. Every second, you do the following:
* Choose the pile with the maximum number of gifts.
* If there is more than one pile with the maximum number of gifts, choose any.
* Leave behind the floor of the square root of the number of... | null |
5 lines simplest code You ever found.Python3 | take-gifts-from-the-richest-pile | 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 array `gifts` denoting the number of gifts in various piles. Every second, you do the following:
* Choose the pile with the maximum number of gifts.
* If there is more than one pile with the maximum number of gifts, choose any.
* Leave behind the floor of the square root of the number of... | null |
Easy | Python Solution | Heap | take-gifts-from-the-richest-pile | 0 | 1 | # Code\n```\nclass Solution:\n def pickGifts(self, gifts: List[int], k: int) -> int:\n res = [-i for i in gifts]\n heapq.heapify(res)\n for i in range(k):\n temp = -heapq.heappop(res)\n temp = int(math.sqrt(temp))\n heapq.heappush(res, -temp)\n ans = [-i f... | 1 | You are given an integer array `gifts` denoting the number of gifts in various piles. Every second, you do the following:
* Choose the pile with the maximum number of gifts.
* If there is more than one pile with the maximum number of gifts, choose any.
* Leave behind the floor of the square root of the number of... | null |
Python 3 || 6 lines, heap, w/ example || T/M: 32 ms / 14.0 MB | take-gifts-from-the-richest-pile | 0 | 1 | "$$heapq.heappushpop(heap, item)$$: Push item on the heap, then pop and return the smallest item from the heap. The combined action runs more efficiently than heappush() followed by a separate call to heappop." -- [https://docs.python.org/3/library/heapq.html]()"\n```\nclass Solution:\n def pickGifts(self, gifts: ... | 4 | You are given an integer array `gifts` denoting the number of gifts in various piles. Every second, you do the following:
* Choose the pile with the maximum number of gifts.
* If there is more than one pile with the maximum number of gifts, choose any.
* Leave behind the floor of the square root of the number of... | null |
[ Python ] ✅✅ Simple Python Solution | 100 % Faster🥳✌👍 | take-gifts-from-the-richest-pile | 0 | 1 | # If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 155 ms, faster than 100.00% of Python3 online submissions for Take Gifts From the Richest Pile.\n# Memory Usage: 14 MB, less than 100.00% of Python3 online submissions for Take Gifts From the Richest Pile.\n\n\n\n# Complexity\n- Time complexity: O(nk)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def pickGifts(self, gifts: List[int], k: int) -> int:\n counter = 0\n while counter < k:... | 1 | You are given an integer array `gifts` denoting the number of gifts in various piles. Every second, you do the following:
* Choose the pile with the maximum number of gifts.
* If there is more than one pile with the maximum number of gifts, choose any.
* Leave behind the floor of the square root of the number of... | null |
Python Solution Using Heap || Easy to Understand for beginners | take-gifts-from-the-richest-pile | 0 | 1 | ```\nfrom heapq import heapify,heappush,heappop\nclass Solution:\n def pickGifts(self, gifts: List[int], k: int) -> int:\n\t\t# python stores element as min heap so 1 will be popped out first instead of 2 to do it reverse multiply each\n\t\t# elements by -1 so -2 will be popped out first\n gifts = [-gift for ... | 1 | You are given an integer array `gifts` denoting the number of gifts in various piles. Every second, you do the following:
* Choose the pile with the maximum number of gifts.
* If there is more than one pile with the maximum number of gifts, choose any.
* Leave behind the floor of the square root of the number of... | null |
Python straightforward solution with prefix sum | count-vowel-strings-in-ranges | 0 | 1 | \n# Code\n```python\nclass Solution:\n def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:\n vowels = \'aeiou\'\n counts = [0] * len(words)\n for i, word in enumerate(words):\n if word[0] in vowels and word[-1] in vowels:\n counts[i] = 1\n ... | 2 | You are given a **0-indexed** array of strings `words` and a 2D array of integers `queries`.
Each query `queries[i] = [li, ri]` asks us to find the number of strings present in the range `li` to `ri` (both **inclusive**) of `words` that start and end with a vowel.
Return _an array_ `ans` _of size_ `queries.length`_, ... | null |
python 3 100% beats | count-vowel-strings-in-ranges | 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** array of strings `words` and a 2D array of integers `queries`.
Each query `queries[i] = [li, ri]` asks us to find the number of strings present in the range `li` to `ri` (both **inclusive**) of `words` that start and end with a vowel.
Return _an array_ `ans` _of size_ `queries.length`_, ... | null |
Python Easy Solution || Beats 96.95% Solutions || Prefix Sum | count-vowel-strings-in-ranges | 0 | 1 | # Python Easy Solution||Prefix Sum||Beats 96.95% Solutions\n\n# Approach\nPreProcess and create the prefix sum array of count of valid words.Valid Words are those words which starts with vowel and ends with vowel.\n\nThen Easily iterate through given queries array and calculate the count of valid words in given range u... | 3 | You are given a **0-indexed** array of strings `words` and a 2D array of integers `queries`.
Each query `queries[i] = [li, ri]` asks us to find the number of strings present in the range `li` to `ri` (both **inclusive**) of `words` that start and end with a vowel.
Return _an array_ `ans` _of size_ `queries.length`_, ... | null |
prefixSum | count-vowel-strings-in-ranges | 0 | 1 | **Cpp**\n```\nclass Solution {\npublic:\n \n bool isVowel(char ch) {\n \n return (ch == \'a\' or ch == \'e\' or ch == \'i\' or ch == \'o\' or ch == \'u\');\n }\n \n vector<int> vowelStrings(vector<string>& words, vector<vector<int>>& queries) {\n \n int n(size(words));\n ... | 2 | You are given a **0-indexed** array of strings `words` and a 2D array of integers `queries`.
Each query `queries[i] = [li, ri]` asks us to find the number of strings present in the range `li` to `ri` (both **inclusive**) of `words` that start and end with a vowel.
Return _an array_ `ans` _of size_ `queries.length`_, ... | null |
✔ Python3 Solution | Prefix Sum | count-vowel-strings-in-ranges | 0 | 1 | # Intution\nIt is a standard range query question which can be solved using `Prefix Sum`\n\n# Approach\nAt index `i` of Array `A` , it contains the no. of words which have first and last character vowel upto `i`. To find the no. of such words we need to subtract the no. words upto `l` from `r`.\n\n# Complexity\n- Time ... | 6 | You are given a **0-indexed** array of strings `words` and a 2D array of integers `queries`.
Each query `queries[i] = [li, ri]` asks us to find the number of strings present in the range `li` to `ri` (both **inclusive**) of `words` that start and end with a vowel.
Return _an array_ `ans` _of size_ `queries.length`_, ... | null |
Python Solution || Easy to Understand for beginners || Prefix sum | count-vowel-strings-in-ranges | 0 | 1 | ```\nclass Solution:\n def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:\n ans = []\n vowels = {\'a\',\'e\',\'i\',\'o\',\'u\'}\n for word in words:\n if word[0] in vowels and word[-1] in vowels:\n ans.append(1)\n else:\n ... | 1 | You are given a **0-indexed** array of strings `words` and a 2D array of integers `queries`.
Each query `queries[i] = [li, ri]` asks us to find the number of strings present in the range `li` to `ri` (both **inclusive**) of `words` that start and end with a vowel.
Return _an array_ `ans` _of size_ `queries.length`_, ... | null |
python3 Solution | house-robber-iv | 0 | 1 | \n```\nclass Solution:\n def minCapability(self, nums: List[int], k: int) -> int:\n n=len(nums)\n def good(target):\n count=0\n i=0\n\n while i<n:\n if nums[i]<=target:\n i+=2\n count+=1\n continue\... | 1 | There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money from the homes, but he **refuses to steal from adjacent homes**.
The **capability** of the robber is the maximum amount of money he steals from one house of all the houses he robbe... | null |
Python3 - Binary Search | house-robber-iv | 0 | 1 | # Intuition\nI got stuck in the same rabbit hole others did\n\nI started with DP - got a TLE\nThen I tried BFS - still got a TLE\nI tried a tweak optimizing for houses you wanted to take from... waan\'t happening\nThen I switched to binary search\n\nThe idea is basically you decide ahead of time how \'bad\' your resul... | 1 | There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money from the homes, but he **refuses to steal from adjacent homes**.
The **capability** of the robber is the maximum amount of money he steals from one house of all the houses he robbe... | null |
[Python 3] Binary search with simple check | house-robber-iv | 0 | 1 | \n\n# Complexity\n- Time complexity: O(Nlog(N))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\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 minCapability(self, nums: List[int], k: int) -> int:\n def check(cap):\n ... | 3 | There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money from the homes, but he **refuses to steal from adjacent homes**.
The **capability** of the robber is the maximum amount of money he steals from one house of all the houses he robbe... | null |
Python 3 || 10 lines, Counter, w/example || T/M: 85% / 50% | rearranging-fruits | 0 | 1 | ```\nclass Solution:\n def minCost(self, basket1: List[int], basket2: List[int]) -> int:\n\n # Example: [4, 4, 4, 4, 3] [5, 5, 5, 5, 3]\n\n c1, c2 = Counter(basket1), Counter(basket2) # c1, c2 = {3:1, 4:4}, {3:1, 5:4}\n c = c1 + c2 ... | 3 | You have two fruit baskets containing `n` fruits each. You are given two **0-indexed** integer arrays `basket1` and `basket2` representing the cost of fruit in each basket. You want to make both baskets **equal**. To do so, you can use the following operation as many times as you want:
* Chose two indices `i` and `j... | null |
[Python3] Use 3-Way Swap to Achieve Smaller Cost | rearranging-fruits | 0 | 1 | # Approach\n1. Count the excess elements in `basket1` and `basket2` that needs to be swapped. Record them in `move1` and `move2`.\n2. Sort `move1` and `move2`, respectively.\n3. The optimal strategy to achieve minimal cost is to take the minimum cost comparing (1) the direct "head/tail" swap using `move1` and `move2` w... | 1 | You have two fruit baskets containing `n` fruits each. You are given two **0-indexed** integer arrays `basket1` and `basket2` representing the cost of fruit in each basket. You want to make both baskets **equal**. To do so, you can use the following operation as many times as you want:
* Chose two indices `i` and `j... | null |
[Python] Simple Solution | Image Explanation | rearranging-fruits | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI start this problem from a simple test case.\n\n\n\n\nGiven two baskets [1, 8, 8] and [1, 9, 9], we have two ch... | 1 | You have two fruit baskets containing `n` fruits each. You are given two **0-indexed** integer arrays `basket1` and `basket2` representing the cost of fruit in each basket. You want to make both baskets **equal**. To do so, you can use the following operation as many times as you want:
* Chose two indices `i` and `j... | null |
✅ Python || Hashtable || Heap. | rearranging-fruits | 0 | 1 | \n# Approach\n1. We compare the count of each element in both baskets and store the differences in a heap. \n1. If the difference is odd, we return -1 because it means we can\'t match the fruits. \n2. If the difference is even, we add half of the difference to the heap, representing the number of unmatched fruit pairs.... | 1 | You have two fruit baskets containing `n` fruits each. You are given two **0-indexed** integer arrays `basket1` and `basket2` representing the cost of fruit in each basket. You want to make both baskets **equal**. To do so, you can use the following operation as many times as you want:
* Chose two indices `i` and `j... | null |
[PYTHON] O(N log N) Count & Sorting Solution | rearranging-fruits | 0 | 1 | # Intuition\nWe can check each elements using counter.\n\nYou can easily come up with exchange two fruits as cheap as possibile.\n\nTo achieve this, the simple idea is to exchage larger value fruits and smaller value fruits.\n\nBut be careful, you have to check the way to exchange via the cheapest fruits. \n\nYou can s... | 9 | You have two fruit baskets containing `n` fruits each. You are given two **0-indexed** integer arrays `basket1` and `basket2` representing the cost of fruit in each basket. You want to make both baskets **equal**. To do so, you can use the following operation as many times as you want:
* Chose two indices `i` and `j... | null |
【C++||Java||Python3】Count and match pairs, O(n) time complexity with quickselect | rearranging-fruits | 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\n# Intuition\n1. If the frequency of each number in the two input arrays is even, then you can always find a way to swap the two array... | 73 | You have two fruit baskets containing `n` fruits each. You are given two **0-indexed** integer arrays `basket1` and `basket2` representing the cost of fruit in each basket. You want to make both baskets **equal**. To do so, you can use the following operation as many times as you want:
* Chose two indices `i` and `j... | null |
Python Frequency Map Approach | Greedy | Easy to Understand | Optimal | rearranging-fruits | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrequency maps were the way to go\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate a frequency map where we increment the occurence of instances for the first basket and decrement for the second one so that t... | 2 | You have two fruit baskets containing `n` fruits each. You are given two **0-indexed** integer arrays `basket1` and `basket2` representing the cost of fruit in each basket. You want to make both baskets **equal**. To do so, you can use the following operation as many times as you want:
* Chose two indices `i` and `j... | null |
Simple O(n * log (n)) runtime solution using sorting [Python] | rearranging-fruits | 0 | 1 | # Intuition\nI reread the problem a few times and it seemed simple enough. Just make swaps so that you eventually have to "identical" sets.\n\n# Approach\nI first reasoned about when we couldn\'t have a solution. The only scenario is if I added up all the frequencies of each fruit, that some fruits counts were not divi... | 0 | You have two fruit baskets containing `n` fruits each. You are given two **0-indexed** integer arrays `basket1` and `basket2` representing the cost of fruit in each basket. You want to make both baskets **equal**. To do so, you can use the following operation as many times as you want:
* Chose two indices `i` and `j... | null |
python3 solution for beginners | rearranging-fruits | 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(nlog(n))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexi... | 0 | You have two fruit baskets containing `n` fruits each. You are given two **0-indexed** integer arrays `basket1` and `basket2` representing the cost of fruit in each basket. You want to make both baskets **equal**. To do so, you can use the following operation as many times as you want:
* Chose two indices `i` and `j... | null |
Simple 100% Fastest Solution | rearranging-fruits | 0 | 1 | # Intuition\nTwo baskets can be made equal if each of them contains several pairs of fruits that are missing in the other. \nThe number of missing pairs in the two baskets is the same.\nSince the cost of swap depends only on the cheap fruit in the pair, you can swap cheap fruits with expensive ones.\nIn addition, you c... | 0 | You have two fruit baskets containing `n` fruits each. You are given two **0-indexed** integer arrays `basket1` and `basket2` representing the cost of fruit in each basket. You want to make both baskets **equal**. To do so, you can use the following operation as many times as you want:
* Chose two indices `i` and `j... | null |
Python Hard | rearranging-fruits | 0 | 1 | ```\nclass Solution:\n def minCost(self, basket1: List[int], basket2: List[int]) -> int:\n N = len(basket1)\n \n \n d = defaultdict(int)\n \n for val in basket1:\n d[val] += 1\n \n for val in basket2:\n d[val] += 1\n \n ... | 0 | You have two fruit baskets containing `n` fruits each. You are given two **0-indexed** integer arrays `basket1` and `basket2` representing the cost of fruit in each basket. You want to make both baskets **equal**. To do so, you can use the following operation as many times as you want:
* Chose two indices `i` and `j... | null |
Python Faster than 100% Stack + HashMap | rearranging-fruits | 0 | 1 | # Intuition\nWe either swap with the min element indirectly or swap with greedily.\n\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 have two fruit baskets containing `n` fruits each. You are given two **0-indexed** integer arrays `basket1` and `basket2` representing the cost of fruit in each basket. You want to make both baskets **equal**. To do so, you can use the following operation as many times as you want:
* Chose two indices `i` and `j... | null |
Easy Python Solution using 2 pointers | find-the-array-concatenation-value | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n left=0\n right=len(nums)-1\n total=0\n while left<=right:\n if left<right:\n total+=int(str(nums[left])+str(nums[right]))\n else:\n total+=nums[l... | 2 | You are given a **0-indexed** integer array `nums`.
The **concatenation** of two numbers is the number formed by concatenating their numerals.
* For example, the concatenation of `15`, `49` is `1549`.
The **concatenation value** of `nums` is initially equal to `0`. Perform this operation until `nums` becomes empty... | null |
BEGINNER FRIENDLY PYTHON PROGRAM [ BEATS 88% OF USERS ] | find-the-array-concatenation-value | 0 | 1 | # Intuition\nUsing for loop and string slicing\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe use for loop to iterate over the list and take the 1st and last elements as string and concatenate\n\n# Code\n```\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n ... | 1 | You are given a **0-indexed** integer array `nums`.
The **concatenation** of two numbers is the number formed by concatenating their numerals.
* For example, the concatenation of `15`, `49` is `1549`.
The **concatenation value** of `nums` is initially equal to `0`. Perform this operation until `nums` becomes empty... | null |
Easy Solution Using While Loop in Python | find-the-array-concatenation-value | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n i=0\n c=0\n j=len(nums)-1\n while(i<=j):\n if(i==j):\n c=c+nums[i]\n break\n s=str(nums[i])+str(nums[j])\n c=c+int(s)\n i=i... | 1 | You are given a **0-indexed** integer array `nums`.
The **concatenation** of two numbers is the number formed by concatenating their numerals.
* For example, the concatenation of `15`, `49` is `1549`.
The **concatenation value** of `nums` is initially equal to `0`. Perform this operation until `nums` becomes empty... | null |
[Python3] simulation | find-the-array-concatenation-value | 0 | 1 | \n```\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n n = len(nums)\n ans = 0 \n for i in range((n+1)//2): \n if i == n-1-i: ans += nums[i]\n else: ans += int(str(nums[i]) + str(nums[n-1-i]))\n return ans \n``` | 1 | You are given a **0-indexed** integer array `nums`.
The **concatenation** of two numbers is the number formed by concatenating their numerals.
* For example, the concatenation of `15`, `49` is `1549`.
The **concatenation value** of `nums` is initially equal to `0`. Perform this operation until `nums` becomes empty... | null |
Python Solution easy to understand || super easy solution | find-the-array-concatenation-value | 0 | 1 | ```\nclass Solution:\n def findTheArrayConcVal(self, num: List[int]) -> int:\n\t\t# to store final sum\n ans = 0\n\t\t# traverse the num array untill its empty\n while num:\n\t\t\t# pop the first element out convert it to string\n p = str(num.pop(0))\n q = ""\n\t\t\t\n\t\t\t# if a... | 1 | You are given a **0-indexed** integer array `nums`.
The **concatenation** of two numbers is the number formed by concatenating their numerals.
* For example, the concatenation of `15`, `49` is `1549`.
The **concatenation value** of `nums` is initially equal to `0`. Perform this operation until `nums` becomes empty... | null |
✅Python3 || C++✅ Beats 100% | find-the-array-concatenation-value | 0 | 1 | \n\n# Please UPVOTE \uD83D\uDE0A\n\n## Python3\n```\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n ans=0\n if len(nums)%2==1:\n ans=nums[len(nums)//2]... | 24 | You are given a **0-indexed** integer array `nums`.
The **concatenation** of two numbers is the number formed by concatenating their numerals.
* For example, the concatenation of `15`, `49` is `1549`.
The **concatenation value** of `nums` is initially equal to `0`. Perform this operation until `nums` becomes empty... | null |
Two pointers Python 3 solution | find-the-array-concatenation-value | 0 | 1 | \n```\nclass Solution:\n def findTheArrayConcVal(self, nums: List[int]) -> int:\n result = 0\n\n p1 = 0\n p2 = len(nums) - 1\n\n while p1 <= p2:\n if p1 == p2:\n result += int(nums[p1])\n\n else:\n result += int(str(nums[p1]) + str(nums[... | 1 | You are given a **0-indexed** integer array `nums`.
The **concatenation** of two numbers is the number formed by concatenating their numerals.
* For example, the concatenation of `15`, `49` is `1549`.
The **concatenation value** of `nums` is initially equal to `0`. Perform this operation until `nums` becomes empty... | null |
Beats 100% Speed easy Python solution | find-the-array-concatenation-value | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You are given a **0-indexed** integer array `nums`.
The **concatenation** of two numbers is the number formed by concatenating their numerals.
* For example, the concatenation of `15`, `49` is `1549`.
The **concatenation value** of `nums` is initially equal to `0`. Perform this operation until `nums` becomes empty... | null |
[Python] A Clean and Short Method Using Binary Search | count-the-number-of-fair-pairs | 0 | 1 | \n# Code\n```\nimport bisect\nclass Solution: \n def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:\n sortingData=[nums[-1]]\n n=len(nums)\n answer=0\n for i in range(n-2, -1, -1):\n l=bisect.bisect_left(sortingData, lower-nums[i])\n u=bise... | 3 | Given a **0-indexed** integer array `nums` of size `n` and two integers `lower` and `upper`, return _the number of fair pairs_.
A pair `(i, j)` is **fair** if:
* `0 <= i < j < n`, and
* `lower <= nums[i] + nums[j] <= upper`
**Example 1:**
**Input:** nums = \[0,1,7,4,4,5\], lower = 3, upper = 6
**Output:** 6
**E... | null |
Sorting + Binary Search --- Python simple solution | count-the-number-of-fair-pairs | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:\n nums.sort()\n cnt = 0\n for i in range(len(nums)-1, -1, -1):\n x = nums[i]\n lo = bisect_left(nums, lower - x, 0, i)\n hi = bisect_right(nums, upper - x... | 1 | Given a **0-indexed** integer array `nums` of size `n` and two integers `lower` and `upper`, return _the number of fair pairs_.
A pair `(i, j)` is **fair** if:
* `0 <= i < j < n`, and
* `lower <= nums[i] + nums[j] <= upper`
**Example 1:**
**Input:** nums = \[0,1,7,4,4,5\], lower = 3, upper = 6
**Output:** 6
**E... | null |
The simplest solution. Binary search with intervals. Python. | count-the-number-of-fair-pairs | 0 | 1 | ****Bold****# 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.... | 1 | Given a **0-indexed** integer array `nums` of size `n` and two integers `lower` and `upper`, return _the number of fair pairs_.
A pair `(i, j)` is **fair** if:
* `0 <= i < j < n`, and
* `lower <= nums[i] + nums[j] <= upper`
**Example 1:**
**Input:** nums = \[0,1,7,4,4,5\], lower = 3, upper = 6
**Output:** 6
**E... | null |
Pop tail before each binary search, O(n log n) | count-the-number-of-fair-pairs | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBinary search lower, and upper\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nPop tail, so it will not count itself.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n ... | 1 | Given a **0-indexed** integer array `nums` of size `n` and two integers `lower` and `upper`, return _the number of fair pairs_.
A pair `(i, j)` is **fair** if:
* `0 <= i < j < n`, and
* `lower <= nums[i] + nums[j] <= upper`
**Example 1:**
**Input:** nums = \[0,1,7,4,4,5\], lower = 3, upper = 6
**Output:** 6
**E... | null |
Two Pointers * 2 | count-the-number-of-fair-pairs | 1 | 1 | Because `nums[i] + nums[j] == nums[j] + nums[i]` the `i < j` condition degrades to `i != j`.\n\nSo, we can sort the array, and use the two-pointer approach to count pairs less than a certain value.\n\nWe do it twice for `uppper` and `lower`, and return the difference.\n\nTime complexity: O(sort)\n\n**C++**\n```cpp\nlon... | 135 | Given a **0-indexed** integer array `nums` of size `n` and two integers `lower` and `upper`, return _the number of fair pairs_.
A pair `(i, j)` is **fair** if:
* `0 <= i < j < n`, and
* `lower <= nums[i] + nums[j] <= upper`
**Example 1:**
**Input:** nums = \[0,1,7,4,4,5\], lower = 3, upper = 6
**Output:** 6
**E... | null |
Simple and Easy Approach with Explanation | count-the-number-of-fair-pairs | 0 | 1 | # Approach:-\n```\nCase 1:- if nums[left] + nums[right] > upper:\nChecking all the cases where sum is greater than upper then simply decrement right by one. If less or equal to the upper value then it satisfy for all case between right to left so add count += right - left and increment in left.\n```\n```\nCase 2:- if n... | 3 | Given a **0-indexed** integer array `nums` of size `n` and two integers `lower` and `upper`, return _the number of fair pairs_.
A pair `(i, j)` is **fair** if:
* `0 <= i < j < n`, and
* `lower <= nums[i] + nums[j] <= upper`
**Example 1:**
**Input:** nums = \[0,1,7,4,4,5\], lower = 3, upper = 6
**Output:** 6
**E... | null |
Python (Simple Two Pointers) | count-the-number-of-fair-pairs | 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 | Given a **0-indexed** integer array `nums` of size `n` and two integers `lower` and `upper`, return _the number of fair pairs_.
A pair `(i, j)` is **fair** if:
* `0 <= i < j < n`, and
* `lower <= nums[i] + nums[j] <= upper`
**Example 1:**
**Input:** nums = \[0,1,7,4,4,5\], lower = 3, upper = 6
**Output:** 6
**E... | null |
✅C++ || Python3✅ sorting , lower and upper | count-the-number-of-fair-pairs | 0 | 1 | # Please Upvote \uD83D\uDE07\n# C++\n```\nclass Solution {\npublic:\n long long countFairPairs(vector<int>& v, int first_val, int last_val) {\n deque<int>vc;\n sort(v.begin(),v.end());\n for(auto i:v) vc.push_back(i);\n long long int ans=0;\n for(int i=0;i<v.size();i++)\n {\... | 53 | Given a **0-indexed** integer array `nums` of size `n` and two integers `lower` and `upper`, return _the number of fair pairs_.
A pair `(i, j)` is **fair** if:
* `0 <= i < j < n`, and
* `lower <= nums[i] + nums[j] <= upper`
**Example 1:**
**Input:** nums = \[0,1,7,4,4,5\], lower = 3, upper = 6
**Output:** 6
**E... | null |
Easy Python solution (with comments) with 2 binary searches. | count-the-number-of-fair-pairs | 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)$$ -->\nO(n ln(n))\n- Space complexity:\n<!-- Add your space complexity here, e.g. ... | 6 | Given a **0-indexed** integer array `nums` of size `n` and two integers `lower` and `upper`, return _the number of fair pairs_.
A pair `(i, j)` is **fair** if:
* `0 <= i < j < n`, and
* `lower <= nums[i] + nums[j] <= upper`
**Example 1:**
**Input:** nums = \[0,1,7,4,4,5\], lower = 3, upper = 6
**Output:** 6
**E... | null |
[Python3] two pointers | count-the-number-of-fair-pairs | 0 | 1 | \n```\nclass Solution:\n def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:\n nums.sort()\n ans = 0 \n lo = hi = len(nums)-1\n for i, x in enumerate(nums): \n while 0 <= hi and x + nums[hi] > upper: hi -= 1\n while 0 <= lo and x + nums[lo] >= l... | 8 | Given a **0-indexed** integer array `nums` of size `n` and two integers `lower` and `upper`, return _the number of fair pairs_.
A pair `(i, j)` is **fair** if:
* `0 <= i < j < n`, and
* `lower <= nums[i] + nums[j] <= upper`
**Example 1:**
**Input:** nums = \[0,1,7,4,4,5\], lower = 3, upper = 6
**Output:** 6
**E... | null |
Python Elegant & Short | Two lines | Bisect | In-place | count-the-number-of-fair-pairs | 0 | 1 | ```\nfrom bisect import bisect, bisect_left\nfrom typing import List\n\n\nclass Solution:\n """\n Time: O(sort)\n Memory: O(1)\n """\n\n def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:\n nums.sort()\n return sum(\n bisect(nums, upper - num, hi=i) - bis... | 1 | Given a **0-indexed** integer array `nums` of size `n` and two integers `lower` and `upper`, return _the number of fair pairs_.
A pair `(i, j)` is **fair** if:
* `0 <= i < j < n`, and
* `lower <= nums[i] + nums[j] <= upper`
**Example 1:**
**Input:** nums = \[0,1,7,4,4,5\], lower = 3, upper = 6
**Output:** 6
**E... | null |
Python 3 || 3 lines, sort and bisect || T/M: 706 ms / 24 MB | count-the-number-of-fair-pairs | 0 | 1 | ```\nclass Solution:\n def countFairPairs(self, nums: list[int], lower: int, upper: int) -> int:\n\n f = lambda x: sum(bisect_right(nums, x - num, hi=i)\n for i, num in enumerate(nums))\n nums.sort()\n\n return f(upper) - f(lower - 1)\n``` | 5 | Given a **0-indexed** integer array `nums` of size `n` and two integers `lower` and `upper`, return _the number of fair pairs_.
A pair `(i, j)` is **fair** if:
* `0 <= i < j < n`, and
* `lower <= nums[i] + nums[j] <= upper`
**Example 1:**
**Input:** nums = \[0,1,7,4,4,5\], lower = 3, upper = 6
**Output:** 6
**E... | null |
[Python3] preprocessing | substring-xor-queries | 0 | 1 | \n```\nclass Solution:\n def substringXorQueries(self, s: str, queries: List[List[int]]) -> List[List[int]]:\n seen = {}\n for i, ch in enumerate(s):\n if ch == \'1\': \n val = 0\n for j in range(i, min(len(s), i+30)): \n val <<= 1\n ... | 2 | You are given a **binary string** `s`, and a **2D** integer array `queries` where `queries[i] = [firsti, secondi]`.
For the `ith` query, find the **shortest substring** of `s` whose **decimal value**, `val`, yields `secondi` when **bitwise XORed** with `firsti`. In other words, `val ^ firsti == secondi`.
The answer t... | null |
Python clean solution | substring-xor-queries | 0 | 1 | use a dict to store numbers we can get from s\n- number 10^9 can be represent with 30 bit\n- for each index i, only need to look forward at most 30 bits\n- for each number, store the shortest substring index\n\n```\nclass Solution:\n def substringXorQueries(self, s: str, queries: List[List[int]]) -> List[List[int]]:... | 1 | You are given a **binary string** `s`, and a **2D** integer array `queries` where `queries[i] = [firsti, secondi]`.
For the `ith` query, find the **shortest substring** of `s` whose **decimal value**, `val`, yields `secondi` when **bitwise XORed** with `firsti`. In other words, `val ^ firsti == secondi`.
The answer t... | null |
Python Logical Solution | substring-xor-queries | 0 | 1 | # Approach\na^b=c => b^c=a\n\n\n# Code\n```\nclass Solution:\n def substringXorQueries(self, s: str, q: List[List[int]]) -> List[List[int]]:\n ot=[]\n n=len(q)\n for i in range(n) :\n het=q[i][0]^q[i][1]\n # print(q[i][0],q[i][1],het)\n x=bin(het)[2:]\n ... | 1 | You are given a **binary string** `s`, and a **2D** integer array `queries` where `queries[i] = [firsti, secondi]`.
For the `ith` query, find the **shortest substring** of `s` whose **decimal value**, `val`, yields `secondi` when **bitwise XORed** with `firsti`. In other words, `val ^ firsti == secondi`.
The answer t... | null |
Python 3 || 6 lines, XOR algebra, w/explanation and example || T/M: 1467 ms / 79 MB | substring-xor-queries | 0 | 1 | Properties of the XOR binary operation:\n```\n \u2022 Associative: (a^b)^c = a^(b^c)\n \u2022 Identity: a^0 = a`\n \u2022 Inverse: a^a = 0\n```\nThese properties imply that the number`val`such that`first^val == second` is `first^second`:\n```\n first^val == second`\n... | 4 | You are given a **binary string** `s`, and a **2D** integer array `queries` where `queries[i] = [firsti, secondi]`.
For the `ith` query, find the **shortest substring** of `s` whose **decimal value**, `val`, yields `secondi` when **bitwise XORed** with `firsti`. In other words, `val ^ firsti == secondi`.
The answer t... | null |
[PYTHON] Simple preprocessing & hashing solution O(N * 32) | substring-xor-queries | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe solution string length can\'t be over 32($2^{32}$).\nThe approach is simple. Just preprocess all the bit string under 32 length.\n\n## Why can we calculate the answer like `a^b` ?\n$$ A \\oplus X = B $$ \n$$ X = A \\oplus B $$ \n\n## Note that w... | 5 | You are given a **binary string** `s`, and a **2D** integer array `queries` where `queries[i] = [firsti, secondi]`.
For the `ith` query, find the **shortest substring** of `s` whose **decimal value**, `val`, yields `secondi` when **bitwise XORed** with `firsti`. In other words, `val ^ firsti == secondi`.
The answer t... | null |
Python3 XOR and dict(map) | substring-xor-queries | 0 | 1 | \n\n\n# Code\n```\nclass Solution:\n def substringXorQueries(self, s: str, v: List[List[int]]) -> List[List[int]]:\n def cmp():\n return -2\n ans=[]\n mp=defaultdict(cmp)\n... | 10 | You are given a **binary string** `s`, and a **2D** integer array `queries` where `queries[i] = [firsti, secondi]`.
For the `ith` query, find the **shortest substring** of `s` whose **decimal value**, `val`, yields `secondi` when **bitwise XORed** with `firsti`. In other words, `val ^ firsti == secondi`.
The answer t... | null |
Python3 clean solution beginner friendly | substring-xor-queries | 0 | 1 | # Intuition\n- Any 10^9 number can be represented by 30 bits, hence we only need to look forward 30 number\n- We can get the target binary to fulfil the query by XOR-ing first and second.\n- Since len(queries) > len(s) by alot it is better to preprocess S into a dict of possible values\n\n# Approach\n- I iterated s fro... | 0 | You are given a **binary string** `s`, and a **2D** integer array `queries` where `queries[i] = [firsti, secondi]`.
For the `ith` query, find the **shortest substring** of `s` whose **decimal value**, `val`, yields `secondi` when **bitwise XORed** with `firsti`. In other words, `val ^ firsti == secondi`.
The answer t... | null |
Python | Beats 100% | O(n) solution | substring-xor-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 a **binary string** `s`, and a **2D** integer array `queries` where `queries[i] = [firsti, secondi]`.
For the `ith` query, find the **shortest substring** of `s` whose **decimal value**, `val`, yields `secondi` when **bitwise XORed** with `firsti`. In other words, `val ^ firsti == secondi`.
The answer t... | null |
Python | substring-xor-queries | 0 | 1 | \n# Code\n```\nclass Solution:\n def substringXorQueries(self, s: str, queries: List[List[int]]) -> List[List[int]]:\n mp = {}\n res = []\n for sub in range(1,31):\n i,j=0,sub\n while j<=len(s):\n mp.setdefault(int(s[i:j],2),(i,j-1))\n i+=1\n ... | 0 | You are given a **binary string** `s`, and a **2D** integer array `queries` where `queries[i] = [firsti, secondi]`.
For the `ith` query, find the **shortest substring** of `s` whose **decimal value**, `val`, yields `secondi` when **bitwise XORed** with `firsti`. In other words, `val ^ firsti == secondi`.
The answer t... | null |
【C++ || Java || Python3】 Binary search in value range | subsequence-with-the-minimum-score | 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\n# Intuition\n1. **Clearly, "remove all" is no worse than "remove some" for selected subsequences.**\n2. Furthermore, if deleting a sh... | 1 | You are given two strings `s` and `t`.
You are allowed to remove any number of characters from the string `t`.
The score of the string is `0` if no characters are removed from the string `t`, otherwise:
* Let `left` be the minimum index among all removed characters.
* Let `right` be the maximum index among all r... | null |
Python | Iterate from both sides | Explanation and Comment | subsequence-with-the-minimum-score | 0 | 1 | First, we consider that given `left` that `t[:left]` is a substring of `s[:sleft]`, how can we find the best `right`?\nOf course, `right` should be as small as possible. Even we delete a ton of character inside `t` but `t[len(t)-1]` is not deleted, the score is still `len(t) - left`.\nThus, we should start with the las... | 1 | You are given two strings `s` and `t`.
You are allowed to remove any number of characters from the string `t`.
The score of the string is `0` if no characters are removed from the string `t`, otherwise:
* Let `left` be the minimum index among all removed characters.
* Let `right` be the maximum index among all r... | null |
Python 3 || 10 lines, two passes || T/M: 174 ms / 18 MB | subsequence-with-the-minimum-score | 0 | 1 | ```\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n\n m, n = len(s), len(t)\n suff, j = [0]*m, n\n\n for i in range(m)[::-1]:\n\n if j > 0 and s[i] == t[j-1]: j -= 1\n suff[i] = j-1\n\n ans, j = j, 0\n\n for i in range(m):\n\n a... | 4 | You are given two strings `s` and `t`.
You are allowed to remove any number of characters from the string `t`.
The score of the string is `0` if no characters are removed from the string `t`, otherwise:
* Let `left` be the minimum index among all removed characters.
* Let `right` be the maximum index among all r... | null |
[Python3] forward & backward | subsequence-with-the-minimum-score | 0 | 1 | \n```\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n suffix = [-1]*len(s)\n j = len(t)-1\n for i in reversed(range(len(s))): \n if 0 <= j and s[i] == t[j]: j -= 1\n suffix[i] = j \n ans = j + 1\n j = 0 \n for i, ch in enumerate(s): ... | 11 | You are given two strings `s` and `t`.
You are allowed to remove any number of characters from the string `t`.
The score of the string is `0` if no characters are removed from the string `t`, otherwise:
* Let `left` be the minimum index among all removed characters.
* Let `right` be the maximum index among all r... | null |
O(n) time and space solution using a queue and a stack | subsequence-with-the-minimum-score | 0 | 1 | # Intuition\n\nMy initial thought was that this should be a dynamic programming problem as it superficially sounds related to the classic longest subsequence problem (e.g., see Cormen\'s Algorithms Text, DP Chapter). However, upon closer inspection, the problem is asking for something much simpler: the minimum distance... | 2 | You are given two strings `s` and `t`.
You are allowed to remove any number of characters from the string `t`.
The score of the string is `0` if no characters are removed from the string `t`, otherwise:
* Let `left` be the minimum index among all removed characters.
* Let `right` be the maximum index among all r... | null |
simple binary search using prefix and suffix arrays O(nlogn) Python 3 | subsequence-with-the-minimum-score | 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`.
You are allowed to remove any number of characters from the string `t`.
The score of the string is `0` if no characters are removed from the string `t`, otherwise:
* Let `left` be the minimum index among all removed characters.
* Let `right` be the maximum index among all r... | null |
Left and Right O(n) -- Python version | subsequence-with-the-minimum-score | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nLeft pass once for each index i in t, find the smallest index j in s such that t[: i+1] is a subsequence of s[: j+1]. Store the answer in an array (leftArr).\nIf such j does not exist for some i, then by default leftArr[i] =... | 0 | You are given two strings `s` and `t`.
You are allowed to remove any number of characters from the string `t`.
The score of the string is `0` if no characters are removed from the string `t`, otherwise:
* Let `left` be the minimum index among all removed characters.
* Let `right` be the maximum index among all r... | null |
Python Solution Using Binary Search | subsequence-with-the-minimum-score | 0 | 1 | # Code\n```\nfrom bisect import bisect_right,bisect_left\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n d=[[] for _ in range(26)]\n for i in range(len(s)):\n d[ord(s[i])-97].append(i)\n j=len(s)\n dp=[-1 for _ in range(len(t))]\n for i in range(len(t... | 0 | You are given two strings `s` and `t`.
You are allowed to remove any number of characters from the string `t`.
The score of the string is `0` if no characters are removed from the string `t`, otherwise:
* Let `left` be the minimum index among all removed characters.
* Let `right` be the maximum index among all r... | null |
2 pointer LEFT - RIGHT | subsequence-with-the-minimum-score | 0 | 1 | \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nlongest increasing prefix+suffix\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<!-- Add your space complexity here, e.g. $$O(n)... | 0 | You are given two strings `s` and `t`.
You are allowed to remove any number of characters from the string `t`.
The score of the string is `0` if no characters are removed from the string `t`, otherwise:
* Let `left` be the minimum index among all removed characters.
* Let `right` be the maximum index among all r... | null |
StraightForward solution | maximum-difference-by-remapping-a-digit | 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)$$ -->\nO(2*n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n... | 1 | You are given an integer `num`. You know that Danny Mittal will sneakily **remap** one of the `10` possible digits (`0` to `9`) to another digit.
Return _the difference between the maximum and minimum_ _values Danny can make by remapping **exactly** **one** digit_ _in_ `num`.
**Notes:**
* When Danny remaps a digit... | null |
🚀 Simple🚀 Greedy🚀 Math 🚀Easy 🚀 Python 🚀Python3 🚀 | maximum-difference-by-remapping-a-digit | 0 | 1 | ### Please Upvote if you find this useful \uD83D\uDE0A\n\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minMaxDifference(self, num: int) -... | 1 | You are given an integer `num`. You know that Danny Mittal will sneakily **remap** one of the `10` possible digits (`0` to `9`) to another digit.
Return _the difference between the maximum and minimum_ _values Danny can make by remapping **exactly** **one** digit_ _in_ `num`.
**Notes:**
* When Danny remaps a digit... | null |
Simple Python3 solution | maximum-difference-by-remapping-a-digit | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def minMaxDifference(self, num: int) -> int:\n string_num = str(num)\n maximum_number = int(string_num)\n minimium_number = 0\n\n for i in string_num:\n if int(i) < 9:\n maximum_number = int(string_num.replace(i, "9"))\n ... | 1 | You are given an integer `num`. You know that Danny Mittal will sneakily **remap** one of the `10` possible digits (`0` to `9`) to another digit.
Return _the difference between the maximum and minimum_ _values Danny can make by remapping **exactly** **one** digit_ _in_ `num`.
**Notes:**
* When Danny remaps a digit... | null |
Python short and clean. | maximum-difference-by-remapping-a-digit | 0 | 1 | # Approach\nWe are allowed to replace one of the 10 possible digits to other.\n\n1. Min number can be formed by replacing the `first digit`, and all other occurences of it, with `0`.\n\n2. Max number can be formed by replacing the `first non 9 digit`, and all other occurences of it with `9`.\n\n3. Return the difference... | 2 | You are given an integer `num`. You know that Danny Mittal will sneakily **remap** one of the `10` possible digits (`0` to `9`) to another digit.
Return _the difference between the maximum and minimum_ _values Danny can make by remapping **exactly** **one** digit_ _in_ `num`.
**Notes:**
* When Danny remaps a digit... | null |
Python | 5 lines of code | maximum-difference-by-remapping-a-digit | 0 | 1 | # Approach\nFor minimal value we always just replace first digit into zero:\n`int(num.replace(num[0], "0")`.\n\nFor maximum value - find first non-9 digit and replace it into 9.\n\n\n# Complexity\n- Time complexity: $$O(1)$$ as we only interate over string with maximum 8 chars. \n<!-- Add your time complexity here, e.g... | 22 | You are given an integer `num`. You know that Danny Mittal will sneakily **remap** one of the `10` possible digits (`0` to `9`) to another digit.
Return _the difference between the maximum and minimum_ _values Danny can make by remapping **exactly** **one** digit_ _in_ `num`.
**Notes:**
* When Danny remaps a digit... | null |
🐍 Super simple Python3 🌟 | EASY, short and sweet 🍫 | O(1) TC and SC | maximum-difference-by-remapping-a-digit | 0 | 1 | # Intuition\nWe will switch the number over to string to make use of python\'s easy string replace. \n\n# Approach\nFor minimal value, always replace the first digit\'s all occurances with \'0\'s.\n\nFor maximal value, replace the first non-\'9\' digit with \'9\'.\n\n# Complexity\nThe lenght of `s` is `log(num, 10)`. A... | 5 | You are given an integer `num`. You know that Danny Mittal will sneakily **remap** one of the `10` possible digits (`0` to `9`) to another digit.
Return _the difference between the maximum and minimum_ _values Danny can make by remapping **exactly** **one** digit_ _in_ `num`.
**Notes:**
* When Danny remaps a digit... | null |
✅ 2 Lines of Code || Explaination💯 | minimum-score-by-changing-two-elements | 0 | 1 | First we will sort the list so we can easily access minimum and maximum values.\n\nThere are total 3 ways in which we can get answer.\n1. By changing First two values - In this case we will chage first two values to make difference zero. Now lowest value we have is nums[2] and largest is nums[-1].\n2. By changing Last ... | 1 | You are given a **0-indexed** integer array `nums`.
* The **low** score of `nums` is the minimum value of `|nums[i] - nums[j]|` over all `0 <= i < j < nums.length`.
* The **high** score of `nums` is the maximum value of `|nums[i] - nums[j]|` over all `0 <= i < j < nums.length`.
* The **score** of `nums` is the s... | null |
Simple Diagram Explanation | minimum-score-by-changing-two-elements | 1 | 1 | # Idea\n- Sort `nums` so that we can easily access maximum and minimum values\n- We will always make the low score $$0$$ by creating duplicate values\n- Now we have changed the question to finding the minimum maximum value difference by changing two values\n- We have three options:\n - Change the two largest values ... | 49 | You are given a **0-indexed** integer array `nums`.
* The **low** score of `nums` is the minimum value of `|nums[i] - nums[j]|` over all `0 <= i < j < nums.length`.
* The **high** score of `nums` is the maximum value of `|nums[i] - nums[j]|` over all `0 <= i < j < nums.length`.
* The **score** of `nums` is the s... | null |
Python short and clean. Beats 100%. 2 solutions. Sorting and Heap. | minimum-score-by-changing-two-elements | 0 | 1 | # Approach 1: Sort\n1. Sort `nums` to `s_nums` for random access to maxes and mins.\n\n2. If there were `0` changes allowed:\n There\'s nothing to do.\n The best we can do is: `s_nums[n - 1] - s_nums[0]`.\n \n Note: Abbriviating `s_num[a] - s_num[b]` as `|a, b|` from henceforth.\n Hence the above becomes... | 2 | You are given a **0-indexed** integer array `nums`.
* The **low** score of `nums` is the minimum value of `|nums[i] - nums[j]|` over all `0 <= i < j < nums.length`.
* The **high** score of `nums` is the maximum value of `|nums[i] - nums[j]|` over all `0 <= i < j < nums.length`.
* The **score** of `nums` is the s... | null |
Python 3 || 2 lines, w/ a terse explanation || T/M: 83% / 100% | minimum-score-by-changing-two-elements | 0 | 1 | ```\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n\n nums.sort()\n\n return min(nums[-1] - nums[2], # [a,b,c, ..., x,y,z] => [c,c,c, ..., x,y,z]\n nums[-2] - nums[1], # [a,b,c, ..., x,y,z] => [b,b,c, ..., x,y,y] \n nums[-3] - nums[0]) # [a,... | 4 | You are given a **0-indexed** integer array `nums`.
* The **low** score of `nums` is the minimum value of `|nums[i] - nums[j]|` over all `0 <= i < j < nums.length`.
* The **high** score of `nums` is the maximum value of `|nums[i] - nums[j]|` over all `0 <= i < j < nums.length`.
* The **score** of `nums` is the s... | null |
Python Solution || 2 lines || Easy to understand | minimum-score-by-changing-two-elements | 0 | 1 | ```\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n n,_ = len(nums),nums.sort()\n return min([nums[n-1]-nums[0],nums[n-3]-nums[0],nums[n-1]-nums[2],nums[n-2]-nums[1]])\n``` | 1 | You are given a **0-indexed** integer array `nums`.
* The **low** score of `nums` is the minimum value of `|nums[i] - nums[j]|` over all `0 <= i < j < nums.length`.
* The **high** score of `nums` is the maximum value of `|nums[i] - nums[j]|` over all `0 <= i < j < nums.length`.
* The **score** of `nums` is the s... | null |
[Python] ✅🔥 2-line Solution w/ Explanation! | minimum-score-by-changing-two-elements | 0 | 1 | ## **Please upvote/favourite/comment if you like this solution!**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis question reduces to minimizing the range of `nums` by changing 2 elements in `nums`. We can minimize the range by doing one of 3 options:\n1. Increase the smallest two numbers. ... | 8 | You are given a **0-indexed** integer array `nums`.
* The **low** score of `nums` is the minimum value of `|nums[i] - nums[j]|` over all `0 <= i < j < nums.length`.
* The **high** score of `nums` is the maximum value of `|nums[i] - nums[j]|` over all `0 <= i < j < nums.length`.
* The **score** of `nums` is the s... | null |
Python | minimum-score-by-changing-two-elements | 0 | 1 | \n# Code\n```\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n nums.sort()\n return min(nums[-2] - nums[1],\n nums[-1] - nums[2],\n nums[-3] - nums[0])\n \n``` | 4 | You are given a **0-indexed** integer array `nums`.
* The **low** score of `nums` is the minimum value of `|nums[i] - nums[j]|` over all `0 <= i < j < nums.length`.
* The **high** score of `nums` is the maximum value of `|nums[i] - nums[j]|` over all `0 <= i < j < nums.length`.
* The **score** of `nums` is the s... | null |
[Python] Simple solution of just checking power of two numbers; Explained | minimum-impossible-or | 0 | 1 | A number can be expressed by some power of two numbers. Thus, we only need to check the power of two numbers in the list, and find the minimum missing one.\n\nTo check the power of two, we can simply do:\n\n`num == num & (-num)`\n\n\n\n```\nclass Solution:\n def minImpossibleOR(self, nums: List[int]) -> int:\n ... | 2 | You are given a **0-indexed** integer array `nums`.
We say that an integer x is **expressible** from `nums` if there exist some integers `0 <= index1 < index2 < ... < indexk < nums.length` for which `nums[index1] | nums[index2] | ... | nums[indexk] = x`. In other words, an integer is expressible if it can be written a... | null |
Python | Simple Solution | minimum-impossible-or | 0 | 1 | # Code\n```\nfrom collections import defaultdict\nclass Solution:\n def minImpossibleOR(self, nums: List[int]) -> int:\n nums = set(nums)\n for i in range(32):\n if (1<<i) not in nums:\n return 1<<i\n \n``` | 1 | You are given a **0-indexed** integer array `nums`.
We say that an integer x is **expressible** from `nums` if there exist some integers `0 <= index1 < index2 < ... < indexk < nums.length` for which `nums[index1] | nums[index2] | ... | nums[indexk] = x`. In other words, an integer is expressible if it can be written a... | null |
Python | Mathematical Induction | Explained | minimum-impossible-or | 0 | 1 | Consider if we don\'t have `1` in `nums`, then the answer is `1` because you cannot use anything larger than `1` to form `1`.\nConsider if we don\'t have `2` in `nums`, then the answer is `2` because you cannot use `1` and anything larger than `2` to form `2`.\nBut if we have [1, 2] in `nums`, we can form `3`.\nSo, by ... | 4 | You are given a **0-indexed** integer array `nums`.
We say that an integer x is **expressible** from `nums` if there exist some integers `0 <= index1 < index2 < ... < indexk < nums.length` for which `nums[index1] | nums[index2] | ... | nums[indexk] = x`. In other words, an integer is expressible if it can be written a... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.