title stringlengths 1 100 | titleSlug stringlengths 3 77 | Java int64 0 1 | Python3 int64 1 1 | content stringlengths 28 44.4k | voteCount int64 0 3.67k | question_content stringlengths 65 5k | question_hints stringclasses 970
values |
|---|---|---|---|---|---|---|---|
Python Short Clean | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCalculate the difference in sum between the two lists. Then put them in the same heap. Pull the biggest difference maker each time from the heap until you compensate for the difference or run the heap out of items.\n\n# Approach\n<!-- Des... | 1 | A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
Yo... | Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one. |
Python Solution | Minimize the differenc | reverse sort the Max sum Arr and forward sort min sum Arr | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\n\nFind the difference between sums of both array, then minimize the difference \n\n# Approach\n\n1) How to minimize the difference ?\n Decrease the value from the max sum arr and increase the value from min sum array\n\n2) how to choose values optimaly from both arrays ?\nopt max value from the max sum... | 0 | You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive.
In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive.
Return _the minimum number of operations ... | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. |
Python Solution | Minimize the differenc | reverse sort the Max sum Arr and forward sort min sum Arr | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\n\nFind the difference between sums of both array, then minimize the difference \n\n# Approach\n\n1) How to minimize the difference ?\n Decrease the value from the max sum arr and increase the value from min sum array\n\n2) how to choose values optimaly from both arrays ?\nopt max value from the max sum... | 0 | A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
Yo... | Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one. |
💋⚡Keep It Simple Stupid. Beats 100% Simplicity, 97% Runtime+Memory. O(N) time, O(1) space. | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\nSince we are dealing with a small discrete number of values (1-6), we create a count dictionary of each set $\\{die: count\\}$. For the smaller set, we can change a die to a six, increasing the sum by $value=6-die$. For the larger set, we can change a die to a one, decreasing the sum by $value=die-1$. Conv... | 0 | You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive.
In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive.
Return _the minimum number of operations ... | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. |
💋⚡Keep It Simple Stupid. Beats 100% Simplicity, 97% Runtime+Memory. O(N) time, O(1) space. | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\nSince we are dealing with a small discrete number of values (1-6), we create a count dictionary of each set $\\{die: count\\}$. For the smaller set, we can change a die to a six, increasing the sum by $value=6-die$. For the larger set, we can change a die to a one, decreasing the sum by $value=die-1$. Conv... | 0 | A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
Yo... | Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one. |
Python O(nlogn) Solution | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | We have two arrays, by calculating the sum, we can know which is larger and which is the smaller.\nTo reach a same sum value (reduce the difference on sum to 0):\n\n- For larger array, at each operation, we want to decrease the number as much as possible.\nSince the min value we can decrease to is 1, at position i, the... | 0 | You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive.
In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive.
Return _the minimum number of operations ... | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. |
Python O(nlogn) Solution | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | We have two arrays, by calculating the sum, we can know which is larger and which is the smaller.\nTo reach a same sum value (reduce the difference on sum to 0):\n\n- For larger array, at each operation, we want to decrease the number as much as possible.\nSince the min value we can decrease to is 1, at position i, the... | 0 | A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
Yo... | Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one. |
In place sort. Find maximum step size. O(n logn) time complexity. O(1) space complexity. | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n\\log n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexi... | 0 | You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive.
In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive.
Return _the minimum number of operations ... | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. |
In place sort. Find maximum step size. O(n logn) time complexity. O(1) space complexity. | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n\\log n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexi... | 0 | A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
Yo... | Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one. |
Optimized Greedy Approach to Minimize Operations for Equal Array Sums | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Minimum Operations to Make Sum of Two Arrays Equal\n\n## Problem Description\n\nYou are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive.\n\nIn one operation, you can change any integer\'s value in any of the arrays to any value b... | 0 | You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive.
In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive.
Return _the minimum number of operations ... | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. |
Optimized Greedy Approach to Minimize Operations for Equal Array Sums | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Minimum Operations to Make Sum of Two Arrays Equal\n\n## Problem Description\n\nYou are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive.\n\nIn one operation, you can change any integer\'s value in any of the arrays to any value b... | 0 | A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
Yo... | Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one. |
Python3 Beats 98.98%, Greedy Solution | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nShould be a greedy problem, because we need to find the most profitable element to turn it either into 1 / 6 to make the sum of both arr the same\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCheck if the argum... | 0 | You are given two arrays of integers `nums1` and `nums2`, possibly of different lengths. The values in the arrays are between `1` and `6`, inclusive.
In one operation, you can change any integer's value in **any** of the arrays to **any** value between `1` and `6`, inclusive.
Return _the minimum number of operations ... | Maintain the next id that should be outputted. Maintain the ids that were inserted in the stream. Per each insert, make a loop where you check if the id that has the turn has been inserted, and if so increment the id that has the turn and continue the loop, else break. |
Python3 Beats 98.98%, Greedy Solution | equal-sum-arrays-with-minimum-number-of-operations | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nShould be a greedy problem, because we need to find the most profitable element to turn it either into 1 / 6 to make the sum of both arr the same\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCheck if the argum... | 0 | A **peak** element in a 2D grid is an element that is **strictly greater** than all of its **adjacent** neighbors to the left, right, top, and bottom.
Given a **0-indexed** `m x n` matrix `mat` where **no two adjacent cells are equal**, find **any** peak element `mat[i][j]` and return _the length 2 array_ `[i,j]`.
Yo... | Let's note that we want to either decrease the sum of the array with a larger sum or increase the array's sum with the smaller sum. You can maintain the largest increase or decrease you can make in a binary search tree and each time get the maximum one. |
Python, Heap and Stack solutions | car-fleet-ii | 0 | 1 | The problem can be solved with a heap or a stack. Heap solution is probably easier to arrive at, given that it only requires us to make two observations about the input, but involves writing more code. Stack solution is elegant and fast, but is harder to come up with, since we have to make more observations about the i... | 12 | There are `n` cars traveling at different speeds in the same direction along a one-lane road. You are given an array `cars` of length `n`, where `cars[i] = [positioni, speedi]` represents:
* `positioni` is the distance between the `ith` car and the beginning of the road in meters. It is guaranteed that `positioni < ... | Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily. |
Python, Heap and Stack solutions | car-fleet-ii | 0 | 1 | The problem can be solved with a heap or a stack. Heap solution is probably easier to arrive at, given that it only requires us to make two observations about the input, but involves writing more code. Stack solution is elegant and fast, but is harder to come up with, since we have to make more observations about the i... | 12 | You are given a **0-indexed** integer array `order` of length `n`, a **permutation** of integers from `1` to `n` representing the **order** of insertion into a **binary search tree**.
A binary search tree is defined as follows:
* The left subtree of a node contains only nodes with keys **less than** the node's key.... | We can simply ignore the merging of any car fleet, simply assume they cross each other. Now the aim is to find the first car to the right, which intersects with the current car before any other. Assume we have already considered all cars to the right already, now the current car is to be considered. Let’s ignore all ca... |
[Python3] | Stack Approach | car-fleet-ii | 0 | 1 | ```\nclass Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n n=len(cars)\n ans=[-1]*n\n stack=[]\n for i in range(n-1,-1,-1):\n while stack and cars[i][1]<=cars[stack[-1]][1]:\n stack.pop()\n while stack:\n ... | 1 | There are `n` cars traveling at different speeds in the same direction along a one-lane road. You are given an array `cars` of length `n`, where `cars[i] = [positioni, speedi]` represents:
* `positioni` is the distance between the `ith` car and the beginning of the road in meters. It is guaranteed that `positioni < ... | Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily. |
[Python3] | Stack Approach | car-fleet-ii | 0 | 1 | ```\nclass Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n n=len(cars)\n ans=[-1]*n\n stack=[]\n for i in range(n-1,-1,-1):\n while stack and cars[i][1]<=cars[stack[-1]][1]:\n stack.pop()\n while stack:\n ... | 1 | You are given a **0-indexed** integer array `order` of length `n`, a **permutation** of integers from `1` to `n` representing the **order** of insertion into a **binary search tree**.
A binary search tree is defined as follows:
* The left subtree of a node contains only nodes with keys **less than** the node's key.... | We can simply ignore the merging of any car fleet, simply assume they cross each other. Now the aim is to find the first car to the right, which intersects with the current car before any other. Assume we have already considered all cars to the right already, now the current car is to be considered. Let’s ignore all ca... |
[Python3] Stack - Time: O(n) & Space: O(n) | car-fleet-ii | 0 | 1 | Time Complexity: O(n)\nSpace Complexity: O(n)\n\nUse stack to store indices and iterate from the back of car array\n\n```\nclass Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n # Stack: go from back and use stack to get ans\n # Time: O(n)\n # Space: O(n)\n ... | 4 | There are `n` cars traveling at different speeds in the same direction along a one-lane road. You are given an array `cars` of length `n`, where `cars[i] = [positioni, speedi]` represents:
* `positioni` is the distance between the `ith` car and the beginning of the road in meters. It is guaranteed that `positioni < ... | Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily. |
[Python3] Stack - Time: O(n) & Space: O(n) | car-fleet-ii | 0 | 1 | Time Complexity: O(n)\nSpace Complexity: O(n)\n\nUse stack to store indices and iterate from the back of car array\n\n```\nclass Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n # Stack: go from back and use stack to get ans\n # Time: O(n)\n # Space: O(n)\n ... | 4 | You are given a **0-indexed** integer array `order` of length `n`, a **permutation** of integers from `1` to `n` representing the **order** of insertion into a **binary search tree**.
A binary search tree is defined as follows:
* The left subtree of a node contains only nodes with keys **less than** the node's key.... | We can simply ignore the merging of any car fleet, simply assume they cross each other. Now the aim is to find the first car to the right, which intersects with the current car before any other. Assume we have already considered all cars to the right already, now the current car is to be considered. Let’s ignore all ca... |
monotonic stack + hashmaop Python 3 | car-fleet-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | There are `n` cars traveling at different speeds in the same direction along a one-lane road. You are given an array `cars` of length `n`, where `cars[i] = [positioni, speedi]` represents:
* `positioni` is the distance between the `ith` car and the beginning of the road in meters. It is guaranteed that `positioni < ... | Think in reverse; instead of finding the minimum prefix + suffix, find the maximum subarray. Finding the maximum subarray is standard and can be done greedily. |
monotonic stack + hashmaop Python 3 | car-fleet-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You are given a **0-indexed** integer array `order` of length `n`, a **permutation** of integers from `1` to `n` representing the **order** of insertion into a **binary search tree**.
A binary search tree is defined as follows:
* The left subtree of a node contains only nodes with keys **less than** the node's key.... | We can simply ignore the merging of any car fleet, simply assume they cross each other. Now the aim is to find the first car to the right, which intersects with the current car before any other. Assume we have already considered all cars to the right already, now the current car is to be considered. Let’s ignore all ca... |
Python3 Easiest and Most understandable solution | find-nearest-point-that-has-the-same-x-or-y-coordinate | 0 | 1 | The solution has three parts, \n1. Checking the validity of the given points.\n2. Finding the smallest Manhattan distance \n3. returning the index of the smallest Manhattan distance \n\nWe check if there are no valid points and return -1\n\n# Code\n```\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, p... | 3 | You are given two integers, `x` and `y`, which represent your current location on a Cartesian grid: `(x, y)`. You are also given an array `points` where each `points[i] = [ai, bi]` represents that a point exists at `(ai, bi)`. A point is **valid** if it shares the same x-coordinate or the same y-coordinate as your loca... | null |
Python3 Easiest and Most understandable solution | find-nearest-point-that-has-the-same-x-or-y-coordinate | 0 | 1 | The solution has three parts, \n1. Checking the validity of the given points.\n2. Finding the smallest Manhattan distance \n3. returning the index of the smallest Manhattan distance \n\nWe check if there are no valid points and return -1\n\n# Code\n```\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, p... | 3 | You are given a binary string `s`. You are allowed to perform two types of operations on the string in any sequence:
* **Type-1: Remove** the character at the start of the string `s` and **append** it to the end of the string.
* **Type-2: Pick** any character in `s` and **flip** its value, i.e., if its value is `'... | Iterate through each point, and keep track of the current point with the smallest Manhattan distance from your current location. |
[Python] Easy solution | find-nearest-point-that-has-the-same-x-or-y-coordinate | 0 | 1 | ```\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:\n minDist = math.inf\n ans = -1\n for i in range(len(points)):\n if points[i][0]==x or points[i][1]==y:\n manDist = abs(points[i][0]-x)+abs(points[i][1]-y)\n ... | 29 | You are given two integers, `x` and `y`, which represent your current location on a Cartesian grid: `(x, y)`. You are also given an array `points` where each `points[i] = [ai, bi]` represents that a point exists at `(ai, bi)`. A point is **valid** if it shares the same x-coordinate or the same y-coordinate as your loca... | null |
[Python] Easy solution | find-nearest-point-that-has-the-same-x-or-y-coordinate | 0 | 1 | ```\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:\n minDist = math.inf\n ans = -1\n for i in range(len(points)):\n if points[i][0]==x or points[i][1]==y:\n manDist = abs(points[i][0]-x)+abs(points[i][1]-y)\n ... | 29 | You are given a binary string `s`. You are allowed to perform two types of operations on the string in any sequence:
* **Type-1: Remove** the character at the start of the string `s` and **append** it to the end of the string.
* **Type-2: Pick** any character in `s` and **flip** its value, i.e., if its value is `'... | Iterate through each point, and keep track of the current point with the smallest Manhattan distance from your current location. |
Python - Clean and Simple! | find-nearest-point-that-has-the-same-x-or-y-coordinate | 0 | 1 | **Solution**:\n```\nclass Solution:\n def nearestValidPoint(self, x1, y1, points):\n minIdx, minDist = -1, inf\n for i,point in enumerate(points):\n x2, y2 = point\n if x1 == x2 or y1 == y2:\n dist = abs(x1-x2) + abs(y1-y2)\n if dist < minDist:\n ... | 5 | You are given two integers, `x` and `y`, which represent your current location on a Cartesian grid: `(x, y)`. You are also given an array `points` where each `points[i] = [ai, bi]` represents that a point exists at `(ai, bi)`. A point is **valid** if it shares the same x-coordinate or the same y-coordinate as your loca... | null |
Python - Clean and Simple! | find-nearest-point-that-has-the-same-x-or-y-coordinate | 0 | 1 | **Solution**:\n```\nclass Solution:\n def nearestValidPoint(self, x1, y1, points):\n minIdx, minDist = -1, inf\n for i,point in enumerate(points):\n x2, y2 = point\n if x1 == x2 or y1 == y2:\n dist = abs(x1-x2) + abs(y1-y2)\n if dist < minDist:\n ... | 5 | You are given a binary string `s`. You are allowed to perform two types of operations on the string in any sequence:
* **Type-1: Remove** the character at the start of the string `s` and **append** it to the end of the string.
* **Type-2: Pick** any character in `s` and **flip** its value, i.e., if its value is `'... | Iterate through each point, and keep track of the current point with the smallest Manhattan distance from your current location. |
Python for beginners 2 solutions | find-nearest-point-that-has-the-same-x-or-y-coordinate | 0 | 1 | ```\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int: \n #Runtime:1167ms\n dic={}\n iterate=0\n for i in points:\n if(i[0]==x or i[1]==y):\n dic[iterate]=dic.get(iterate,0)+(abs(i[0]-x)+abs(i[1]-y))\n ite... | 1 | You are given two integers, `x` and `y`, which represent your current location on a Cartesian grid: `(x, y)`. You are also given an array `points` where each `points[i] = [ai, bi]` represents that a point exists at `(ai, bi)`. A point is **valid** if it shares the same x-coordinate or the same y-coordinate as your loca... | null |
Python for beginners 2 solutions | find-nearest-point-that-has-the-same-x-or-y-coordinate | 0 | 1 | ```\nclass Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int: \n #Runtime:1167ms\n dic={}\n iterate=0\n for i in points:\n if(i[0]==x or i[1]==y):\n dic[iterate]=dic.get(iterate,0)+(abs(i[0]-x)+abs(i[1]-y))\n ite... | 1 | You are given a binary string `s`. You are allowed to perform two types of operations on the string in any sequence:
* **Type-1: Remove** the character at the start of the string `s` and **append** it to the end of the string.
* **Type-2: Pick** any character in `s` and **flip** its value, i.e., if its value is `'... | Iterate through each point, and keep track of the current point with the smallest Manhattan distance from your current location. |
Easy Python solution | check-if-number-is-a-sum-of-powers-of-three | 0 | 1 | \n# Code\n```\nclass Solution:\n def checkPowersOfThree(self, n: int) -> bool:\n sm=0\n val=16\n while val>=0:\n tmp=3**val\n if sm+tmp<n:\n sm+=tmp\n elif sm+tmp==n:return True\n val-=1\n return False\n``` | 3 | Given an integer `n`, return `true` _if it is possible to represent_ `n` _as the sum of distinct powers of three._ Otherwise, return `false`.
An integer `y` is a power of three if there exists an integer `x` such that `y == 3x`.
**Example 1:**
**Input:** n = 12
**Output:** true
**Explanation:** 12 = 31 + 32
**Examp... | Traverse the graph visiting root, left, root, right, root to make an Euler Path Return the node (LCA) that is at the lowest depth between p and q in the Euler Path |
Easy Python solution | check-if-number-is-a-sum-of-powers-of-three | 0 | 1 | \n# Code\n```\nclass Solution:\n def checkPowersOfThree(self, n: int) -> bool:\n sm=0\n val=16\n while val>=0:\n tmp=3**val\n if sm+tmp<n:\n sm+=tmp\n elif sm+tmp==n:return True\n val-=1\n return False\n``` | 3 | You have `n` packages that you are trying to place in boxes, **one package in each box**. There are `m` suppliers that each produce boxes of **different sizes** (with infinite supply). A package can be placed in a box if the size of the package is **less than or equal to** the size of the box.
The package sizes are gi... | Let's note that the maximum power of 3 you'll use in your soln is 3^16 The number can not be represented as a sum of powers of 3 if it's ternary presentation has a 2 in it |
Python recursive solution with explanation | check-if-number-is-a-sum-of-powers-of-three | 0 | 1 | # Intuition\nThe problem requires us to check if the given integer n can be represented as a sum of distinct powers of 3. One way to approach this problem is to keep dividing the given number by 3 and check if the remainder is either 0 or 1. If we encounter a remainder of 2, we can directly return False as it cannot be... | 1 | Given an integer `n`, return `true` _if it is possible to represent_ `n` _as the sum of distinct powers of three._ Otherwise, return `false`.
An integer `y` is a power of three if there exists an integer `x` such that `y == 3x`.
**Example 1:**
**Input:** n = 12
**Output:** true
**Explanation:** 12 = 31 + 32
**Examp... | Traverse the graph visiting root, left, root, right, root to make an Euler Path Return the node (LCA) that is at the lowest depth between p and q in the Euler Path |
Python recursive solution with explanation | check-if-number-is-a-sum-of-powers-of-three | 0 | 1 | # Intuition\nThe problem requires us to check if the given integer n can be represented as a sum of distinct powers of 3. One way to approach this problem is to keep dividing the given number by 3 and check if the remainder is either 0 or 1. If we encounter a remainder of 2, we can directly return False as it cannot be... | 1 | You have `n` packages that you are trying to place in boxes, **one package in each box**. There are `m` suppliers that each produce boxes of **different sizes** (with infinite supply). A package can be placed in a box if the size of the package is **less than or equal to** the size of the box.
The package sizes are gi... | Let's note that the maximum power of 3 you'll use in your soln is 3^16 The number can not be represented as a sum of powers of 3 if it's ternary presentation has a 2 in it |
Python | Simple | check-if-number-is-a-sum-of-powers-of-three | 0 | 1 | \n def checkPowersOfThree(self, n: int) -> bool:\n while n > 0:\n if n%3 == 2:\n return False\n n //= 3\n return True | 1 | Given an integer `n`, return `true` _if it is possible to represent_ `n` _as the sum of distinct powers of three._ Otherwise, return `false`.
An integer `y` is a power of three if there exists an integer `x` such that `y == 3x`.
**Example 1:**
**Input:** n = 12
**Output:** true
**Explanation:** 12 = 31 + 32
**Examp... | Traverse the graph visiting root, left, root, right, root to make an Euler Path Return the node (LCA) that is at the lowest depth between p and q in the Euler Path |
Python | Simple | check-if-number-is-a-sum-of-powers-of-three | 0 | 1 | \n def checkPowersOfThree(self, n: int) -> bool:\n while n > 0:\n if n%3 == 2:\n return False\n n //= 3\n return True | 1 | You have `n` packages that you are trying to place in boxes, **one package in each box**. There are `m` suppliers that each produce boxes of **different sizes** (with infinite supply). A package can be placed in a box if the size of the package is **less than or equal to** the size of the box.
The package sizes are gi... | Let's note that the maximum power of 3 you'll use in your soln is 3^16 The number can not be represented as a sum of powers of 3 if it's ternary presentation has a 2 in it |
Python very easy Solution in O(log(n,3)) and O(1) 4 Line of Code | check-if-number-is-a-sum-of-powers-of-three | 0 | 1 | # Code\n```\nclass Solution:\n def checkPowersOfThree(self, n: int) -> bool:\n while(n!=0):\n if(n%3>1):return False\n n//=3\n return True\n``` | 1 | Given an integer `n`, return `true` _if it is possible to represent_ `n` _as the sum of distinct powers of three._ Otherwise, return `false`.
An integer `y` is a power of three if there exists an integer `x` such that `y == 3x`.
**Example 1:**
**Input:** n = 12
**Output:** true
**Explanation:** 12 = 31 + 32
**Examp... | Traverse the graph visiting root, left, root, right, root to make an Euler Path Return the node (LCA) that is at the lowest depth between p and q in the Euler Path |
Python very easy Solution in O(log(n,3)) and O(1) 4 Line of Code | check-if-number-is-a-sum-of-powers-of-three | 0 | 1 | # Code\n```\nclass Solution:\n def checkPowersOfThree(self, n: int) -> bool:\n while(n!=0):\n if(n%3>1):return False\n n//=3\n return True\n``` | 1 | You have `n` packages that you are trying to place in boxes, **one package in each box**. There are `m` suppliers that each produce boxes of **different sizes** (with infinite supply). A package can be placed in a box if the size of the package is **less than or equal to** the size of the box.
The package sizes are gi... | Let's note that the maximum power of 3 you'll use in your soln is 3^16 The number can not be represented as a sum of powers of 3 if it's ternary presentation has a 2 in it |
Beats 100% - O(N^2) | Python | only using dictionary | sum-of-beauty-of-all-substrings | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe use a frequency groups and frequency dictionary to keep track of min and max frequency in string as we check all poosible \n# Approach\n<!-- Describe your approach to solving the problem. -->\nEach time we traverse from i+1 to n we kee... | 3 | The **beauty** of a string is the difference in frequencies between the most frequent and least frequent characters.
* For example, the beauty of `"abaacc "` is `3 - 1 = 2`.
Given a string `s`, return _the sum of **beauty** of all of its substrings._
**Example 1:**
**Input:** s = "aabcb "
**Output:** 5
**Explana... | Concatenate all strings in the first array into a single string in the given order, the same for the second array. Both arrays represent the same string if and only if the generated strings are the same. |
[Python3] freq table | sum-of-beauty-of-all-substrings | 0 | 1 | \n```\nclass Solution:\n def beautySum(self, s: str) -> int:\n ans = 0 \n for i in range(len(s)):\n freq = [0]*26\n for j in range(i, len(s)):\n freq[ord(s[j])-97] += 1\n ans += max(freq) - min(x for x in freq if x)\n return ans \n``` | 55 | The **beauty** of a string is the difference in frequencies between the most frequent and least frequent characters.
* For example, the beauty of `"abaacc "` is `3 - 1 = 2`.
Given a string `s`, return _the sum of **beauty** of all of its substrings._
**Example 1:**
**Input:** s = "aabcb "
**Output:** 5
**Explana... | Concatenate all strings in the first array into a single string in the given order, the same for the second array. Both arrays represent the same string if and only if the generated strings are the same. |
Python Easy Explanation(Beats 95%) | sum-of-beauty-of-all-substrings | 0 | 1 | # Intuition\nIn substring problems we try to generate all substrings and calculate what is asked of them. Most of the time we need to optimize the inner loop to reduce the time complexity for required solution.\n\n# Approach\n1. The problem wants us to find the sum of beauty(diff b/w most frequent and least frequent c... | 0 | The **beauty** of a string is the difference in frequencies between the most frequent and least frequent characters.
* For example, the beauty of `"abaacc "` is `3 - 1 = 2`.
Given a string `s`, return _the sum of **beauty** of all of its substrings._
**Example 1:**
**Input:** s = "aabcb "
**Output:** 5
**Explana... | Concatenate all strings in the first array into a single string in the given order, the same for the second array. Both arrays represent the same string if and only if the generated strings are the same. |
Python 3 || Counters || T/M: 100%/88% | count-pairs-of-nodes | 0 | 1 | ```\nclass Solution:\n def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:\n \n nodes = Counter(chain(*edges))\n nodes = {i:nodes[i] if i in nodes else 0 for i in range(1, n+1)}\n edges = Counter(map(lambda x:(min(x), max(x)), edges))\n \n ... | 4 | You are given an undirected graph defined by an integer `n`, the number of nodes, and a 2D integer array `edges`, the edges in the graph, where `edges[i] = [ui, vi]` indicates that there is an **undirected** edge between `ui` and `vi`. You are also given an integer array `queries`.
Let `incident(a, b)` be defined as t... | Think greedily. If you build the string from the end to the beginning, it will always be optimal to put the highest possible character at the current index. |
[Python3] 2-pointer | count-pairs-of-nodes | 0 | 1 | \n```\nclass Solution:\n def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:\n degree = [0]*n\n freq = defaultdict(int)\n for u, v in edges: \n degree[u-1] += 1\n degree[v-1] += 1\n freq[min(u-1, v-1), max(u-1, v-1)] += 1\n ... | 19 | You are given an undirected graph defined by an integer `n`, the number of nodes, and a 2D integer array `edges`, the edges in the graph, where `edges[i] = [ui, vi]` indicates that there is an **undirected** edge between `ui` and `vi`. You are also given an integer array `queries`.
Let `incident(a, b)` be defined as t... | Think greedily. If you build the string from the end to the beginning, it will always be optimal to put the highest possible character at the current index. |
Python Easy Approach | Faster than 99% | O(20*N) | count-pairs-of-nodes | 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 undirected graph defined by an integer `n`, the number of nodes, and a 2D integer array `edges`, the edges in the graph, where `edges[i] = [ui, vi]` indicates that there is an **undirected** edge between `ui` and `vi`. You are also given an integer array `queries`.
Let `incident(a, b)` be defined as t... | Think greedily. If you build the string from the end to the beginning, it will always be optimal to put the highest possible character at the current index. |
prefix sum of valid pairs based on number of incidents mapping to number of pairs per query | count-pairs-of-nodes | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI claim no intuition for this one. It stumped me and I needed to go and break apart the current best answer to get an answer that would work and build up from there. Hopefully someday I\'m at the point to build this from scratch, but at t... | 0 | You are given an undirected graph defined by an integer `n`, the number of nodes, and a 2D integer array `edges`, the edges in the graph, where `edges[i] = [ui, vi]` indicates that there is an **undirected** edge between `ui` and `vi`. You are also given an integer array `queries`.
Let `incident(a, b)` be defined as t... | Think greedily. If you build the string from the end to the beginning, it will always be optimal to put the highest possible character at the current index. |
[Python 3] Simple solution | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthe string is not leading by \'0\', it means it starts by \'1\'. Thus the satisfy string has the form \'1111...0\' or \'1111...111\'. Thus there must not exist \'01\' form in correct string, otherwise it is false\n\n# Approach\n<!-- Descr... | 4 | Given a binary string `s` **without leading zeros**, return `true` _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "1001 "
**Output:** false
**Explanation:** The ones do not form a contiguous segment.
**Example 2:**
**Input:** s = "1... | We can easily figure that the f(x) : does x solve this array is monotonic so binary Search is doable Figure a sorting pattern |
[Python 3] Simple solution | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthe string is not leading by \'0\', it means it starts by \'1\'. Thus the satisfy string has the form \'1111...0\' or \'1111...111\'. Thus there must not exist \'01\' form in correct string, otherwise it is false\n\n# Approach\n<!-- Descr... | 4 | Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed:
* Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`.
Return `s` _after removing all occurrences of_ `part`.
A **substring** is a contiguous seque... | It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones. |
[Python 3] - Check for "01" (1 Liner) | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | **Solution 1**: Check for ```"01"```\nSince the input string cannot ```s``` cannot have any leading zeroes and must contain ```at most one contiguous segment of 1s```, we need to check if ```"01"``` is present in ```s``` or not. If it is present, we can return False, else True.\n\nA few testcases to help understand the... | 38 | Given a binary string `s` **without leading zeros**, return `true` _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "1001 "
**Output:** false
**Explanation:** The ones do not form a contiguous segment.
**Example 2:**
**Input:** s = "1... | We can easily figure that the f(x) : does x solve this array is monotonic so binary Search is doable Figure a sorting pattern |
[Python 3] - Check for "01" (1 Liner) | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | **Solution 1**: Check for ```"01"```\nSince the input string cannot ```s``` cannot have any leading zeroes and must contain ```at most one contiguous segment of 1s```, we need to check if ```"01"``` is present in ```s``` or not. If it is present, we can return False, else True.\n\nA few testcases to help understand the... | 38 | Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed:
* Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`.
Return `s` _after removing all occurrences of_ `part`.
A **substring** is a contiguous seque... | It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones. |
Python3 one liner and explanatory solution | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def checkOnesSegment(self, s: str) -> bool:\n #1st Approach\n # for i in range(len(s)):\n # if s[i] == \'0\':\n # if s[i:].count(\'1\') > 0:\n # return False\n # return True\n\n #2nd Approach\n # return... | 2 | Given a binary string `s` **without leading zeros**, return `true` _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "1001 "
**Output:** false
**Explanation:** The ones do not form a contiguous segment.
**Example 2:**
**Input:** s = "1... | We can easily figure that the f(x) : does x solve this array is monotonic so binary Search is doable Figure a sorting pattern |
Python3 one liner and explanatory solution | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def checkOnesSegment(self, s: str) -> bool:\n #1st Approach\n # for i in range(len(s)):\n # if s[i] == \'0\':\n # if s[i:].count(\'1\') > 0:\n # return False\n # return True\n\n #2nd Approach\n # return... | 2 | Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed:
* Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`.
Return `s` _after removing all occurrences of_ `part`.
A **substring** is a contiguous seque... | It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones. |
Python regex easy solution | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given a binary string `s` **without leading zeros**, return `true` _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "1001 "
**Output:** false
**Explanation:** The ones do not form a contiguous segment.
**Example 2:**
**Input:** s = "1... | We can easily figure that the f(x) : does x solve this array is monotonic so binary Search is doable Figure a sorting pattern |
Python regex easy solution | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed:
* Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`.
Return `s` _after removing all occurrences of_ `part`.
A **substring** is a contiguous seque... | It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones. |
Check if Binary String Has at Most One Segment of Ones | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given a binary string `s` **without leading zeros**, return `true` _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "1001 "
**Output:** false
**Explanation:** The ones do not form a contiguous segment.
**Example 2:**
**Input:** s = "1... | We can easily figure that the f(x) : does x solve this array is monotonic so binary Search is doable Figure a sorting pattern |
Check if Binary String Has at Most One Segment of Ones | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed:
* Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`.
Return `s` _after removing all occurrences of_ `part`.
A **substring** is a contiguous seque... | It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones. |
A python solution | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given a binary string `s` **without leading zeros**, return `true` _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "1001 "
**Output:** false
**Explanation:** The ones do not form a contiguous segment.
**Example 2:**
**Input:** s = "1... | We can easily figure that the f(x) : does x solve this array is monotonic so binary Search is doable Figure a sorting pattern |
A python solution | check-if-binary-string-has-at-most-one-segment-of-ones | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given two strings `s` and `part`, perform the following operation on `s` until **all** occurrences of the substring `part` are removed:
* Find the **leftmost** occurrence of the substring `part` and **remove** it from `s`.
Return `s` _after removing all occurrences of_ `part`.
A **substring** is a contiguous seque... | It's guaranteed to have at least one segment The string size is small so you can count all segments of ones with no that have no adjacent ones. |
Python Elegant & Short | 1-Line | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nfrom math import ceil\n\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return ceil(abs(sum(nums) - goal) / limit)\n\n``` | 1 | You are given an integer array `nums` and two integers `limit` and `goal`. The array `nums` has an interesting property that `abs(nums[i]) <= limit`.
Return _the minimum number of elements you need to add to make the sum of the array equal to_ `goal`. The array must maintain its property that `abs(nums[i]) <= limit`.
... | null |
Python Elegant & Short | 1-Line | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```\nfrom math import ceil\n\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return ceil(abs(sum(nums) - goal) / limit)\n\n``` | 1 | The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices.
* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`.
Given an array `nums`, return _the **maximum alternating sum** of any... | Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can "normalize" goal by offsetting it by the... |
Python 3 | 1-liner | Explanation | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | ### Explanation\n- Find the absolute difference\n- Add new numbers using `limit`, count how many numbers need to be added using `ceil`\n### Implementation\n```\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return math.ceil(abs(goal - sum(nums)) / limit)\n``` | 6 | You are given an integer array `nums` and two integers `limit` and `goal`. The array `nums` has an interesting property that `abs(nums[i]) <= limit`.
Return _the minimum number of elements you need to add to make the sum of the array equal to_ `goal`. The array must maintain its property that `abs(nums[i]) <= limit`.
... | null |
Python 3 | 1-liner | Explanation | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | ### Explanation\n- Find the absolute difference\n- Add new numbers using `limit`, count how many numbers need to be added using `ceil`\n### Implementation\n```\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return math.ceil(abs(goal - sum(nums)) / limit)\n``` | 6 | The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices.
* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`.
Given an array `nums`, return _the **maximum alternating sum** of any... | Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can "normalize" goal by offsetting it by the... |
One line Python answer | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | # Code\n```\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return abs(sum(nums)-goal)//limit if abs(sum(nums)-goal)%limit==0 else abs(sum(nums)-goal)//limit+1\n``` | 0 | You are given an integer array `nums` and two integers `limit` and `goal`. The array `nums` has an interesting property that `abs(nums[i]) <= limit`.
Return _the minimum number of elements you need to add to make the sum of the array equal to_ `goal`. The array must maintain its property that `abs(nums[i]) <= limit`.
... | null |
One line Python answer | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | # Code\n```\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return abs(sum(nums)-goal)//limit if abs(sum(nums)-goal)%limit==0 else abs(sum(nums)-goal)//limit+1\n``` | 0 | The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices.
* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`.
Given an array `nums`, return _the **maximum alternating sum** of any... | Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can "normalize" goal by offsetting it by the... |
Half Liner LOL | Beginner Friendly Explanations | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | # Explanation\nBrute force some examples and it will become clear that the difference ```diff``` (how much should we add to reach ```goal```) can be either +/-. And it does not matter.\n\nReason is because to reach the goal, we must add numbers. Now as this is not a proof, we can say that the sign of the difference dep... | 0 | You are given an integer array `nums` and two integers `limit` and `goal`. The array `nums` has an interesting property that `abs(nums[i]) <= limit`.
Return _the minimum number of elements you need to add to make the sum of the array equal to_ `goal`. The array must maintain its property that `abs(nums[i]) <= limit`.
... | null |
Half Liner LOL | Beginner Friendly Explanations | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | # Explanation\nBrute force some examples and it will become clear that the difference ```diff``` (how much should we add to reach ```goal```) can be either +/-. And it does not matter.\n\nReason is because to reach the goal, we must add numbers. Now as this is not a proof, we can say that the sign of the difference dep... | 0 | The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices.
* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`.
Given an array `nums`, return _the **maximum alternating sum** of any... | Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can "normalize" goal by offsetting it by the... |
Python - one line | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | # Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return 0 if sum(nums) == goal else ceil(abs(goal - sum(nums)) / limit)\n \n``` | 0 | You are given an integer array `nums` and two integers `limit` and `goal`. The array `nums` has an interesting property that `abs(nums[i]) <= limit`.
Return _the minimum number of elements you need to add to make the sum of the array equal to_ `goal`. The array must maintain its property that `abs(nums[i]) <= limit`.
... | null |
Python - one line | minimum-elements-to-add-to-form-a-given-sum | 0 | 1 | # Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return 0 if sum(nums) == goal else ceil(abs(goal - sum(nums)) / limit)\n \n``` | 0 | The **alternating sum** of a **0-indexed** array is defined as the **sum** of the elements at **even** indices **minus** the **sum** of the elements at **odd** indices.
* For example, the alternating sum of `[4,2,5,3]` is `(4 + 5) - (2 + 3) = 4`.
Given an array `nums`, return _the **maximum alternating sum** of any... | Try thinking about the problem as if the array is empty. Then you only need to form goal using elements whose absolute value is <= limit. You can greedily set all of the elements except one to limit or -limit, so the number of elements you need is ceil(abs(goal)/ limit). You can "normalize" goal by offsetting it by the... |
[Python3] Dijkstra + Cache DFS ~ DP Top-down Memorization - Simple | number-of-restricted-paths-from-first-to-last-node | 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(V)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(V + E)$$\n<!-- Add your space complexity ... | 3 | There is an undirected weighted connected graph. You are given a positive integer `n` which denotes that the graph has `n` nodes labeled from `1` to `n`, and an array `edges` where each `edges[i] = [ui, vi, weighti]` denotes that there is an edge between nodes `ui` and `vi` with weight equal to `weighti`.
A path from ... | A string is incorrect if it contains a character that is not allowed Constraints are small enough for brute force |
[Python3] Dijkstra + Cache DFS ~ DP Top-down Memorization - Simple | number-of-restricted-paths-from-first-to-last-node | 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(V)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(V + E)$$\n<!-- Add your space complexity ... | 3 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi,... | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in... |
[Python3] Dijkstra + dp | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | \n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = {} # graph as adjacency list \n for u, v, w in edges: \n graph.setdefault(u, []).append((v, w))\n graph.setdefault(v, []).append((u, w))\n \n queue = [n]\n ... | 4 | There is an undirected weighted connected graph. You are given a positive integer `n` which denotes that the graph has `n` nodes labeled from `1` to `n`, and an array `edges` where each `edges[i] = [ui, vi, weighti]` denotes that there is an edge between nodes `ui` and `vi` with weight equal to `weighti`.
A path from ... | A string is incorrect if it contains a character that is not allowed Constraints are small enough for brute force |
[Python3] Dijkstra + dp | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | \n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = {} # graph as adjacency list \n for u, v, w in edges: \n graph.setdefault(u, []).append((v, w))\n graph.setdefault(v, []).append((u, w))\n \n queue = [n]\n ... | 4 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi,... | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in... |
Python 3 | Dijkstra, DFS, DAG pruning | Explanation | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | ### Implementation\n- The solution is basically an implementation based on `hint`, please seee below comments for detail\n### Explanation\n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = collections.defaultdict(list) # build graph\n for a, b... | 3 | There is an undirected weighted connected graph. You are given a positive integer `n` which denotes that the graph has `n` nodes labeled from `1` to `n`, and an array `edges` where each `edges[i] = [ui, vi, weighti]` denotes that there is an edge between nodes `ui` and `vi` with weight equal to `weighti`.
A path from ... | A string is incorrect if it contains a character that is not allowed Constraints are small enough for brute force |
Python 3 | Dijkstra, DFS, DAG pruning | Explanation | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | ### Implementation\n- The solution is basically an implementation based on `hint`, please seee below comments for detail\n### Explanation\n```\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = collections.defaultdict(list) # build graph\n for a, b... | 3 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi,... | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in... |
similar to 1976. Number of Ways to Arrive at Destination | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Find all dist from node i to n\n- use dfs top down + memo to find how many ways\n- restricted path is non-increasing path from node 1 to n, not shortest path\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Comp... | 0 | There is an undirected weighted connected graph. You are given a positive integer `n` which denotes that the graph has `n` nodes labeled from `1` to `n`, and an array `edges` where each `edges[i] = [ui, vi, weighti]` denotes that there is an edge between nodes `ui` and `vi` with weight equal to `weighti`.
A path from ... | A string is incorrect if it contains a character that is not allowed Constraints are small enough for brute force |
similar to 1976. Number of Ways to Arrive at Destination | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Find all dist from node i to n\n- use dfs top down + memo to find how many ways\n- restricted path is non-increasing path from node 1 to n, not shortest path\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Comp... | 0 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi,... | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in... |
Python 3 | Very fast | Dijkstra algo + DP (dfs + memoization) | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | \n\n\n# Code\n```\nclass Solution:\n\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n \n def count_path_from(node, mod):\n ... | 0 | There is an undirected weighted connected graph. You are given a positive integer `n` which denotes that the graph has `n` nodes labeled from `1` to `n`, and an array `edges` where each `edges[i] = [ui, vi, weighti]` denotes that there is an edge between nodes `ui` and `vi` with weight equal to `weighti`.
A path from ... | A string is incorrect if it contains a character that is not allowed Constraints are small enough for brute force |
Python 3 | Very fast | Dijkstra algo + DP (dfs + memoization) | number-of-restricted-paths-from-first-to-last-node | 0 | 1 | \n\n\n# Code\n```\nclass Solution:\n\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n \n def count_path_from(node, mod):\n ... | 0 | You have a movie renting company consisting of `n` shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array `entries` where `entries[i] = [shopi,... | Run a Dijkstra from node numbered n to compute distance from the last node. Consider all edges [u, v] one by one and direct them such that distance of u to n > distance of v to n. If both u and v are at the same distance from n, discard this edge. Now this problem reduces to computing the number of paths from 1 to n in... |
[Python3] Dynamic Programming and Optimizations | make-the-xor-of-all-segments-equal-to-zero | 0 | 1 | The first observation we need to make is that the moving window of size k must cycle. When a new element enter the window from the right, the same element must leave from the left.\n\nNow, we need to decide which element to place in each position of the window. Since the position of every element in `nums[i::k]` should... | 51 | You are given an array `nums` and an integer `k`. The XOR of a segment `[left, right]` where `left <= right` is the `XOR` of all the elements with indices between `left` and `right`, inclusive: `nums[left] XOR nums[left+1] XOR ... XOR nums[right]`.
Return _the minimum number of elements to change in the array_... | Absolute difference is the same as max(a, b) - min(a, b). How can you use this fact with the fact that the array is sorted? For nums[i], the answer is (nums[i] - nums[0]) + (nums[i] - nums[1]) + ... + (nums[i] - nums[i-1]) + (nums[i+1] - nums[i]) + (nums[i+2] - nums[i]) + ... + (nums[n-1] - nums[i]). It can be simplifi... |
[Python3] Dynamic Programming and Optimizations | make-the-xor-of-all-segments-equal-to-zero | 0 | 1 | The first observation we need to make is that the moving window of size k must cycle. When a new element enter the window from the right, the same element must leave from the left.\n\nNow, we need to decide which element to place in each position of the window. Since the position of every element in `nums[i::k]` should... | 51 | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product differ... | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. |
DP Solution | make-the-xor-of-all-segments-equal-to-zero | 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 array `nums` and an integer `k`. The XOR of a segment `[left, right]` where `left <= right` is the `XOR` of all the elements with indices between `left` and `right`, inclusive: `nums[left] XOR nums[left+1] XOR ... XOR nums[right]`.
Return _the minimum number of elements to change in the array_... | Absolute difference is the same as max(a, b) - min(a, b). How can you use this fact with the fact that the array is sorted? For nums[i], the answer is (nums[i] - nums[0]) + (nums[i] - nums[1]) + ... + (nums[i] - nums[i-1]) + (nums[i+1] - nums[i]) + (nums[i+2] - nums[i]) + ... + (nums[n-1] - nums[i]). It can be simplifi... |
DP Solution | make-the-xor-of-all-segments-equal-to-zero | 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 | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product differ... | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. |
[Python3] dp | make-the-xor-of-all-segments-equal-to-zero | 0 | 1 | I learned the solution from the posts of others. This damn problem is sooooo hard! \n\n```\nclass Solution:\n def minChanges(self, nums: List[int], k: int) -> int:\n freq = defaultdict(lambda: defaultdict(int))\n for i, x in enumerate(nums): freq[i%k][x] += 1 # freq by row\n \n n = 1 << 1... | 3 | You are given an array `nums` and an integer `k`. The XOR of a segment `[left, right]` where `left <= right` is the `XOR` of all the elements with indices between `left` and `right`, inclusive: `nums[left] XOR nums[left+1] XOR ... XOR nums[right]`.
Return _the minimum number of elements to change in the array_... | Absolute difference is the same as max(a, b) - min(a, b). How can you use this fact with the fact that the array is sorted? For nums[i], the answer is (nums[i] - nums[0]) + (nums[i] - nums[1]) + ... + (nums[i] - nums[i-1]) + (nums[i+1] - nums[i]) + (nums[i+2] - nums[i]) + ... + (nums[n-1] - nums[i]). It can be simplifi... |
[Python3] dp | make-the-xor-of-all-segments-equal-to-zero | 0 | 1 | I learned the solution from the posts of others. This damn problem is sooooo hard! \n\n```\nclass Solution:\n def minChanges(self, nums: List[int], k: int) -> int:\n freq = defaultdict(lambda: defaultdict(int))\n for i, x in enumerate(nums): freq[i%k][x] += 1 # freq by row\n \n n = 1 << 1... | 3 | The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product differ... | Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them. |
[Python3] check diff | check-if-one-string-swap-can-make-strings-equal | 0 | 1 | \n```\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n diff = [[x, y] for x, y in zip(s1, s2) if x != y]\n return not diff or len(diff) == 2 and diff[0][::-1] == diff[1]\n``` | 80 | You are given two strings `s1` and `s2` of equal length. A **string swap** is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return `true` _if it is possible to make both strings equal by performing **at most one string swap** on **exactly on... | Store the path from p to the root. Traverse the path from q to the root, the first common point of the two paths is the LCA. |
[Python3] check diff | check-if-one-string-swap-can-make-strings-equal | 0 | 1 | \n```\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n diff = [[x, y] for x, y in zip(s1, s2) if x != y]\n return not diff or len(diff) == 2 and diff[0][::-1] == diff[1]\n``` | 80 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-e... | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
Python | Easy Solution✅ | check-if-one-string-swap-can-make-strings-equal | 0 | 1 | ```\ndef areAlmostEqual(self, s1: str, s2: str) -> bool:\n if s1 == s2:\n return True # if strings are equal then swaping is not required\n if sorted(s1) != sorted(s2):\n return False # if sorted s1 and s2 are not equal then swaping will not make strings equal\n \n ... | 39 | You are given two strings `s1` and `s2` of equal length. A **string swap** is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return `true` _if it is possible to make both strings equal by performing **at most one string swap** on **exactly on... | Store the path from p to the root. Traverse the path from q to the root, the first common point of the two paths is the LCA. |
Python | Easy Solution✅ | check-if-one-string-swap-can-make-strings-equal | 0 | 1 | ```\ndef areAlmostEqual(self, s1: str, s2: str) -> bool:\n if s1 == s2:\n return True # if strings are equal then swaping is not required\n if sorted(s1) != sorted(s2):\n return False # if sorted s1 and s2 are not equal then swaping will not make strings equal\n \n ... | 39 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-e... | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
[python]--\easiest soln\ | check-if-one-string-swap-can-make-strings-equal | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n \n if s1==s2: #strings are equal no swapping required\n return True\n if sorted(s1)!=sorted(s2): #if alphabets of strings are not equal\n return False\n countof=0\n for i ... | 3 | You are given two strings `s1` and `s2` of equal length. A **string swap** is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return `true` _if it is possible to make both strings equal by performing **at most one string swap** on **exactly on... | Store the path from p to the root. Traverse the path from q to the root, the first common point of the two paths is the LCA. |
[python]--\easiest soln\ | check-if-one-string-swap-can-make-strings-equal | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n \n if s1==s2: #strings are equal no swapping required\n return True\n if sorted(s1)!=sorted(s2): #if alphabets of strings are not equal\n return False\n countof=0\n for i ... | 3 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-e... | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
Python solution using Dictionary | check-if-one-string-swap-can-make-strings-equal | 0 | 1 | # Code\n```\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n c=0\n d={}\n dd={}\n for i in range(len(s1)):\n if s1[i] not in d:\n d[s1[i]]=1\n else:\n d[s1[i]]+=1\n if s2[i] not in dd:\n ... | 3 | You are given two strings `s1` and `s2` of equal length. A **string swap** is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return `true` _if it is possible to make both strings equal by performing **at most one string swap** on **exactly on... | Store the path from p to the root. Traverse the path from q to the root, the first common point of the two paths is the LCA. |
Python solution using Dictionary | check-if-one-string-swap-can-make-strings-equal | 0 | 1 | # Code\n```\nclass Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n c=0\n d={}\n dd={}\n for i in range(len(s1)):\n if s1[i] not in d:\n d[s1[i]]=1\n else:\n d[s1[i]]+=1\n if s2[i] not in dd:\n ... | 3 | A **wonderful** string is a string where **at most one** letter appears an **odd** number of times.
* For example, `"ccjjc "` and `"abab "` are wonderful, but `"ab "` is not.
Given a string `word` that consists of the first ten lowercase English letters (`'a'` through `'j'`), return _the **number of wonderful non-e... | The answer is false if the number of nonequal positions in the strings is not equal to 0 or 2. Check that these positions have the same set of characters. |
One Line of Code Awesome Logic | find-center-of-star-graph | 0 | 1 | \n\n# 1. Awesome Logic----->One Line Code\n```\nclass Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n return list(set(edges[0]) & set(edges[1]))[0]\n\n #please upvote me it would encourage me alot\n\n```\n# 2. Check first value and Second Value\n```\nclass Solution:\n def findCenter(s... | 17 | There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node.
You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that th... | Calculate the wealth of each customer Find the maximum element in array. |
One Line of Code Awesome Logic | find-center-of-star-graph | 0 | 1 | \n\n# 1. Awesome Logic----->One Line Code\n```\nclass Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n return list(set(edges[0]) & set(edges[1]))[0]\n\n #please upvote me it would encourage me alot\n\n```\n# 2. Check first value and Second Value\n```\nclass Solution:\n def findCenter(s... | 17 | You are an ant tasked with adding `n` new rooms numbered `0` to `n-1` to your colony. You are given the expansion plan as a **0-indexed** integer array of length `n`, `prevRoom`, where `prevRoom[i]` indicates that you must build room `prevRoom[i]` before building room `i`, and these two rooms must be connected **direct... | The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center. |
Easiest 1 liner Python O(1) solution ................. | find-center-of-star-graph | 0 | 1 | ```class Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n if edges[0][0]==edges[1][0] or edges[0][0]==edges[1][1]:\n return edges[0][0]\n return edges[0][1]\n```\nReducing it to one liner......\n```class Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n ... | 10 | There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node.
You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that th... | Calculate the wealth of each customer Find the maximum element in array. |
Easiest 1 liner Python O(1) solution ................. | find-center-of-star-graph | 0 | 1 | ```class Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n if edges[0][0]==edges[1][0] or edges[0][0]==edges[1][1]:\n return edges[0][0]\n return edges[0][1]\n```\nReducing it to one liner......\n```class Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n ... | 10 | You are an ant tasked with adding `n` new rooms numbered `0` to `n-1` to your colony. You are given the expansion plan as a **0-indexed** integer array of length `n`, `prevRoom`, where `prevRoom[i]` indicates that you must build room `prevRoom[i]` before building room `i`, and these two rooms must be connected **direct... | The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center. |
Python 1 Liner | find-center-of-star-graph | 0 | 1 | ```\nclass Solution(object):\n def findCenter(self, edges):\n return edges[0][0] if edges[0][0] in edges[1] else edges[0][1]\n``` | 3 | There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node.
You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that th... | Calculate the wealth of each customer Find the maximum element in array. |
Python 1 Liner | find-center-of-star-graph | 0 | 1 | ```\nclass Solution(object):\n def findCenter(self, edges):\n return edges[0][0] if edges[0][0] in edges[1] else edges[0][1]\n``` | 3 | You are an ant tasked with adding `n` new rooms numbered `0` to `n-1` to your colony. You are given the expansion plan as a **0-indexed** integer array of length `n`, `prevRoom`, where `prevRoom[i]` indicates that you must build room `prevRoom[i]` before building room `i`, and these two rooms must be connected **direct... | The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center. |
3 Python Solutions | find-center-of-star-graph | 0 | 1 | ```\ndef findCenter(self, e: List[List[int]]) -> int:\n\treturn (set(e[0]) & set(e[1])).pop()\n```\n\t\t\n```\ndef findCenter(self, e: List[List[int]]) -> int:\n\tif e[0][0]==e[1][0] or e[0][0]==e[1][1]:\n\t\treturn e[0][0]\n\treturn e[0][1]\n```\n\n```\ndef findCenter(self, e: List[List[int]]) -> int:\n\treturn e[0][e... | 19 | There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node.
You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that th... | Calculate the wealth of each customer Find the maximum element in array. |
3 Python Solutions | find-center-of-star-graph | 0 | 1 | ```\ndef findCenter(self, e: List[List[int]]) -> int:\n\treturn (set(e[0]) & set(e[1])).pop()\n```\n\t\t\n```\ndef findCenter(self, e: List[List[int]]) -> int:\n\tif e[0][0]==e[1][0] or e[0][0]==e[1][1]:\n\t\treturn e[0][0]\n\treturn e[0][1]\n```\n\n```\ndef findCenter(self, e: List[List[int]]) -> int:\n\treturn e[0][e... | 19 | You are an ant tasked with adding `n` new rooms numbered `0` to `n-1` to your colony. You are given the expansion plan as a **0-indexed** integer array of length `n`, `prevRoom`, where `prevRoom[i]` indicates that you must build room `prevRoom[i]` before building room `i`, and these two rooms must be connected **direct... | The center is the only node that has more than one edge. The center is also connected to all other nodes. Any two edges must have a common node, which is the center. |
[Python3] - Pythonic Heap-Loop | maximum-average-pass-ratio | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe should always put a good students into a class where the passing guarantees the best improvement.\n\nAs this improvement changes with putting a student into a class, we can utilize a priority with the improvement as a main key.\n# Appr... | 1 | There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where `classes[i] = [passi, totali]`. You know beforehand that in the `ith` class, there are `totali` total students, but only `passi` number of students will pass the exam.
You are al... | In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right? |
[Python] 100% Efficient solution, easy to understand with comments and explanation | maximum-average-pass-ratio | 0 | 1 | **Key Idea:** We need to keep assigning the remaining extra students to the class which can experience the greatest impact. \n\nLet see an example below, if we have following clasess - [[2,4], [3,9], [4,5], [2,10]], then the impact of assignment students to each class can be defined as,\n\n```\n# In simple terms it can... | 16 | There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where `classes[i] = [passi, totali]`. You know beforehand that in the `ith` class, there are `totali` total students, but only `passi` number of students will pass the exam.
You are al... | In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.