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] heap | max-value-of-equation | 0 | 1 | Algo\nSince the target to be optimized is `yi + yj + |xi - xj|` (aka `xj + yj + yi - xi` given `j > i`), the value of interest is `yi - xi`. While we loop through the array with index `j`, we want to keep track of the largest `yi - xi` under the constraint that `xj - xi <= k`. \n\nWe could use a priority queue for this... | 9 | Write an API that generates fancy sequences using the `append`, `addAll`, and `multAll` operations.
Implement the `Fancy` class:
* `Fancy()` Initializes the object with an empty sequence.
* `void append(val)` Appends an integer `val` to the end of the sequence.
* `void addAll(inc)` Increments all existing value... | Use a priority queue to store for each point i, the tuple [yi-xi, xi] Loop through the array and pop elements from the heap if the condition xj - xi > k, where j is the current index and i is the point on top the queue. After popping elements from the queue. If the queue is not empty, calculate the equation with the cu... |
Python Bruteforce and MonoQueue completely Explained | max-value-of-equation | 0 | 1 | This is my first post.Please show some love if you found this helpful.The basic idea is very simple for the bruteforce solution.For every pair of (i,j) caluclate the value of equation and return the maximum answer at the end.The second solution deals with two pointers and monoque structures.If you are unfamiliar with m... | 8 | You are given an array `points` containing the coordinates of points on a 2D plane, sorted by the x-values, where `points[i] = [xi, yi]` such that `xi < xj` for all `1 <= i < j <= points.length`. You are also given an integer `k`.
Return _the maximum value of the equation_ `yi + yj + |xi - xj|` where `|xi - xj| <= k` ... | Keep track of the engineers by their efficiency in decreasing order. Starting from one engineer, to build a team, it suffices to bring K-1 more engineers who have higher efficiencies as well as high speeds. |
Python Bruteforce and MonoQueue completely Explained | max-value-of-equation | 0 | 1 | This is my first post.Please show some love if you found this helpful.The basic idea is very simple for the bruteforce solution.For every pair of (i,j) caluclate the value of equation and return the maximum answer at the end.The second solution deals with two pointers and monoque structures.If you are unfamiliar with m... | 8 | Write an API that generates fancy sequences using the `append`, `addAll`, and `multAll` operations.
Implement the `Fancy` class:
* `Fancy()` Initializes the object with an empty sequence.
* `void append(val)` Appends an integer `val` to the end of the sequence.
* `void addAll(inc)` Increments all existing value... | Use a priority queue to store for each point i, the tuple [yi-xi, xi] Loop through the array and pop elements from the heap if the condition xj - xi > k, where j is the current index and i is the point on top the queue. After popping elements from the queue. If the queue is not empty, calculate the equation with the cu... |
Easiest Deque solution O(n) TC and O(n) SC | max-value-of-equation | 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 `points` containing the coordinates of points on a 2D plane, sorted by the x-values, where `points[i] = [xi, yi]` such that `xi < xj` for all `1 <= i < j <= points.length`. You are also given an integer `k`.
Return _the maximum value of the equation_ `yi + yj + |xi - xj|` where `|xi - xj| <= k` ... | Keep track of the engineers by their efficiency in decreasing order. Starting from one engineer, to build a team, it suffices to bring K-1 more engineers who have higher efficiencies as well as high speeds. |
Easiest Deque solution O(n) TC and O(n) SC | max-value-of-equation | 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 | Write an API that generates fancy sequences using the `append`, `addAll`, and `multAll` operations.
Implement the `Fancy` class:
* `Fancy()` Initializes the object with an empty sequence.
* `void append(val)` Appends an integer `val` to the end of the sequence.
* `void addAll(inc)` Increments all existing value... | Use a priority queue to store for each point i, the tuple [yi-xi, xi] Loop through the array and pop elements from the heap if the condition xj - xi > k, where j is the current index and i is the point on top the queue. After popping elements from the queue. If the queue is not empty, calculate the equation with the cu... |
Double heap, python | max-value-of-equation | 0 | 1 | # Intuition\n\nThe question is to find\n$$\n \\max (x_j+y_j-\\min\\{(x_i-y_i):i<j,\\,x_j-k\\leq x_i\\})\n$$\nThe `MinSet` class implements the constrained running minimum using two heaps, one for the values seen before $j$, and one for the values that already went out of the window ($x_i<x_j-k$). \n\n# Complexity\n\... | 0 | You are given an array `points` containing the coordinates of points on a 2D plane, sorted by the x-values, where `points[i] = [xi, yi]` such that `xi < xj` for all `1 <= i < j <= points.length`. You are also given an integer `k`.
Return _the maximum value of the equation_ `yi + yj + |xi - xj|` where `|xi - xj| <= k` ... | Keep track of the engineers by their efficiency in decreasing order. Starting from one engineer, to build a team, it suffices to bring K-1 more engineers who have higher efficiencies as well as high speeds. |
Double heap, python | max-value-of-equation | 0 | 1 | # Intuition\n\nThe question is to find\n$$\n \\max (x_j+y_j-\\min\\{(x_i-y_i):i<j,\\,x_j-k\\leq x_i\\})\n$$\nThe `MinSet` class implements the constrained running minimum using two heaps, one for the values seen before $j$, and one for the values that already went out of the window ($x_i<x_j-k$). \n\n# Complexity\n\... | 0 | Write an API that generates fancy sequences using the `append`, `addAll`, and `multAll` operations.
Implement the `Fancy` class:
* `Fancy()` Initializes the object with an empty sequence.
* `void append(val)` Appends an integer `val` to the end of the sequence.
* `void addAll(inc)` Increments all existing value... | Use a priority queue to store for each point i, the tuple [yi-xi, xi] Loop through the array and pop elements from the heap if the condition xj - xi > k, where j is the current index and i is the point on top the queue. After popping elements from the queue. If the queue is not empty, calculate the equation with the cu... |
Python + Java Solution || Using sorting | can-make-arithmetic-progression-from-sequence | 1 | 1 | # Approach\nSimply sort the array and check the differnce between current element element and previous element , if the diff is same through out the array then it forms arthimetic sequence otherwise it will returns false.\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(1)\n```java []\n public ... | 2 | A sequence of numbers is called an **arithmetic progression** if the difference between any two consecutive elements is the same.
Given an array of numbers `arr`, return `true` _if the array can be rearranged to form an **arithmetic progression**. Otherwise, return_ `false`.
**Example 1:**
**Input:** arr = \[3,5,1\]... | If the s.length < k we cannot construct k strings from s and answer is false. If the number of characters that have odd counts is > k then the minimum number of palindrome strings we can construct is > k and answer is false. Otherwise you can construct exactly k palindrome strings and answer is true (why ?). |
Python + Java Solution || Using sorting | can-make-arithmetic-progression-from-sequence | 1 | 1 | # Approach\nSimply sort the array and check the differnce between current element element and previous element , if the diff is same through out the array then it forms arthimetic sequence otherwise it will returns false.\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(1)\n```java []\n public ... | 2 | You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the **sum** of scores of all the players in the team.
However, the basketball team is not allowed to have **conflicts**. A **conflict** exists if a younger player ... | Consider that any valid arithmetic progression will be in sorted order. Sort the array, then check if the differences of all consecutive elements are equal. |
Simple 2 liner in Python | can-make-arithmetic-progression-from-sequence | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def canMakeArithmeticProgression(self, arr: List[int]) -> bool:\n arr.sort()\n return all(arr[i]-arr[i+1] == arr[0]-arr[1] for i in range(len(arr)-1))\n``` | 1 | A sequence of numbers is called an **arithmetic progression** if the difference between any two consecutive elements is the same.
Given an array of numbers `arr`, return `true` _if the array can be rearranged to form an **arithmetic progression**. Otherwise, return_ `false`.
**Example 1:**
**Input:** arr = \[3,5,1\]... | If the s.length < k we cannot construct k strings from s and answer is false. If the number of characters that have odd counts is > k then the minimum number of palindrome strings we can construct is > k and answer is false. Otherwise you can construct exactly k palindrome strings and answer is true (why ?). |
Simple 2 liner in Python | can-make-arithmetic-progression-from-sequence | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def canMakeArithmeticProgression(self, arr: List[int]) -> bool:\n arr.sort()\n return all(arr[i]-arr[i+1] == arr[0]-arr[1] for i in range(len(arr)-1))\n``` | 1 | You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the **sum** of scores of all the players in the team.
However, the basketball team is not allowed to have **conflicts**. A **conflict** exists if a younger player ... | Consider that any valid arithmetic progression will be in sorted order. Sort the array, then check if the differences of all consecutive elements are equal. |
Python3 Solution | can-make-arithmetic-progression-from-sequence | 0 | 1 | \n```\nclass Solution:\n def canMakeArithmeticProgression(self, arr: List[int]) -> bool:\n arr.sort()\n for x,y in zip(arr,arr[1:]):\n if y-x!=arr[1]-arr[0]:\n return False\n\n return True \n``` | 1 | A sequence of numbers is called an **arithmetic progression** if the difference between any two consecutive elements is the same.
Given an array of numbers `arr`, return `true` _if the array can be rearranged to form an **arithmetic progression**. Otherwise, return_ `false`.
**Example 1:**
**Input:** arr = \[3,5,1\]... | If the s.length < k we cannot construct k strings from s and answer is false. If the number of characters that have odd counts is > k then the minimum number of palindrome strings we can construct is > k and answer is false. Otherwise you can construct exactly k palindrome strings and answer is true (why ?). |
Python3 Solution | can-make-arithmetic-progression-from-sequence | 0 | 1 | \n```\nclass Solution:\n def canMakeArithmeticProgression(self, arr: List[int]) -> bool:\n arr.sort()\n for x,y in zip(arr,arr[1:]):\n if y-x!=arr[1]-arr[0]:\n return False\n\n return True \n``` | 1 | You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the **sum** of scores of all the players in the team.
However, the basketball team is not allowed to have **conflicts**. A **conflict** exists if a younger player ... | Consider that any valid arithmetic progression will be in sorted order. Sort the array, then check if the differences of all consecutive elements are equal. |
Simple and optimal python3 solution | can-make-arithmetic-progression-from-sequence | 0 | 1 | # Complexity\n- Time complexity: $$O(n \\cdot log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$ (because of TimSort)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nimport itertools\n\nclass Solution:\n def canMakeArithmeticProgression... | 1 | A sequence of numbers is called an **arithmetic progression** if the difference between any two consecutive elements is the same.
Given an array of numbers `arr`, return `true` _if the array can be rearranged to form an **arithmetic progression**. Otherwise, return_ `false`.
**Example 1:**
**Input:** arr = \[3,5,1\]... | If the s.length < k we cannot construct k strings from s and answer is false. If the number of characters that have odd counts is > k then the minimum number of palindrome strings we can construct is > k and answer is false. Otherwise you can construct exactly k palindrome strings and answer is true (why ?). |
Simple and optimal python3 solution | can-make-arithmetic-progression-from-sequence | 0 | 1 | # Complexity\n- Time complexity: $$O(n \\cdot log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$ (because of TimSort)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nimport itertools\n\nclass Solution:\n def canMakeArithmeticProgression... | 1 | You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the **sum** of scores of all the players in the team.
However, the basketball team is not allowed to have **conflicts**. A **conflict** exists if a younger player ... | Consider that any valid arithmetic progression will be in sorted order. Sort the array, then check if the differences of all consecutive elements are equal. |
Python3 29ms very fast solution | can-make-arithmetic-progression-from-sequence | 0 | 1 | # Code\n```\nclass Solution:\n def canMakeArithmeticProgression(self, arr: List[int]) -> bool:\n arr = sorted(arr)\n count, current, apnum = 0, 0, arr[1] - arr[0]\n\n for i in range(len(arr)-1):\n current = apnum + arr[i]\n if current == arr[i+1]:\n count = c... | 1 | A sequence of numbers is called an **arithmetic progression** if the difference between any two consecutive elements is the same.
Given an array of numbers `arr`, return `true` _if the array can be rearranged to form an **arithmetic progression**. Otherwise, return_ `false`.
**Example 1:**
**Input:** arr = \[3,5,1\]... | If the s.length < k we cannot construct k strings from s and answer is false. If the number of characters that have odd counts is > k then the minimum number of palindrome strings we can construct is > k and answer is false. Otherwise you can construct exactly k palindrome strings and answer is true (why ?). |
Python3 29ms very fast solution | can-make-arithmetic-progression-from-sequence | 0 | 1 | # Code\n```\nclass Solution:\n def canMakeArithmeticProgression(self, arr: List[int]) -> bool:\n arr = sorted(arr)\n count, current, apnum = 0, 0, arr[1] - arr[0]\n\n for i in range(len(arr)-1):\n current = apnum + arr[i]\n if current == arr[i+1]:\n count = c... | 1 | You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the **sum** of scores of all the players in the team.
However, the basketball team is not allowed to have **conflicts**. A **conflict** exists if a younger player ... | Consider that any valid arithmetic progression will be in sorted order. Sort the array, then check if the differences of all consecutive elements are equal. |
C++ 3 lines & python 1 line|| physics | last-moment-before-all-ants-fall-out-of-a-plank | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI don\'t like this description. If you use moving balls instead, it just reflects the physics.(I am just borrowing concepts from physics and have no intention of discussing the size of the moving ball and its possible physical properties.... | 10 | We have a wooden plank of the length `n` **units**. Some ants are walking on the plank, each ant moves with a speed of **1 unit per second**. Some of the ants move to the **left**, the other move to the **right**.
When two ants moving in two **different** directions meet at some point, they change their directions and... | Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum. If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Ot... |
C++ 3 lines & python 1 line|| physics | last-moment-before-all-ants-fall-out-of-a-plank | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI don\'t like this description. If you use moving balls instead, it just reflects the physics.(I am just borrowing concepts from physics and have no intention of discussing the size of the moving ball and its possible physical properties.... | 10 | We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an ... | The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction. |
✅For Beginners ✅II O(n) II just for loop✅ | last-moment-before-all-ants-fall-out-of-a-plank | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe given code defines a class Solution with a method getLastMoment that calculates the last moment when a particle at position n will hit a wall. The particle is initially located at position 0 and can move either to the left or the righ... | 46 | We have a wooden plank of the length `n` **units**. Some ants are walking on the plank, each ant moves with a speed of **1 unit per second**. Some of the ants move to the **left**, the other move to the **right**.
When two ants moving in two **different** directions meet at some point, they change their directions and... | Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum. If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Ot... |
✅For Beginners ✅II O(n) II just for loop✅ | last-moment-before-all-ants-fall-out-of-a-plank | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe given code defines a class Solution with a method getLastMoment that calculates the last moment when a particle at position n will hit a wall. The particle is initially located at position 0 and can move either to the left or the righ... | 46 | We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an ... | The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction. |
🔥More than one way |🔥Detailed Explanations | Java | C++ | Python | JavaScript | C# | | last-moment-before-all-ants-fall-out-of-a-plank | 1 | 1 | ### The first method is the best, while the second method is just for your curiosity.\n\n>If you want to understand How to think for this solution ? \nAfter explaining 2nd mehtod i had explained below at last\n\n# 1st Method :- Two Passes\uD83D\uDD25\n\n## Intuition \uD83D\uDE80\nThe problem involves ants moving on a w... | 77 | We have a wooden plank of the length `n` **units**. Some ants are walking on the plank, each ant moves with a speed of **1 unit per second**. Some of the ants move to the **left**, the other move to the **right**.
When two ants moving in two **different** directions meet at some point, they change their directions and... | Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum. If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Ot... |
🔥More than one way |🔥Detailed Explanations | Java | C++ | Python | JavaScript | C# | | last-moment-before-all-ants-fall-out-of-a-plank | 1 | 1 | ### The first method is the best, while the second method is just for your curiosity.\n\n>If you want to understand How to think for this solution ? \nAfter explaining 2nd mehtod i had explained below at last\n\n# 1st Method :- Two Passes\uD83D\uDD25\n\n## Intuition \uD83D\uDE80\nThe problem involves ants moving on a w... | 77 | We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an ... | The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction. |
Python3 Solution | last-moment-before-all-ants-fall-out-of-a-plank | 0 | 1 | \n```\nclass Solution:\n def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int:\n ans=0\n for i in left:\n ans=max(i,ans)\n for i in right:\n ans=max(n-i,ans)\n return ans \n``` | 4 | We have a wooden plank of the length `n` **units**. Some ants are walking on the plank, each ant moves with a speed of **1 unit per second**. Some of the ants move to the **left**, the other move to the **right**.
When two ants moving in two **different** directions meet at some point, they change their directions and... | Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum. If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Ot... |
Python3 Solution | last-moment-before-all-ants-fall-out-of-a-plank | 0 | 1 | \n```\nclass Solution:\n def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int:\n ans=0\n for i in left:\n ans=max(i,ans)\n for i in right:\n ans=max(n-i,ans)\n return ans \n``` | 4 | We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an ... | The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction. |
faster than 95.7% of solutions greedy | last-moment-before-all-ants-fall-out-of-a-plank | 0 | 1 | \n# Intuition\nThe first thought I had on how to solve this problem was to find the maximum time taken by the ants to fall off the plank. Since the ants move with a speed of 1 unit per second, the maximum time taken by the ants to fall off the plank is the maximum distance between the ants and the ends of the plank.\n\... | 3 | We have a wooden plank of the length `n` **units**. Some ants are walking on the plank, each ant moves with a speed of **1 unit per second**. Some of the ants move to the **left**, the other move to the **right**.
When two ants moving in two **different** directions meet at some point, they change their directions and... | Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum. If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Ot... |
faster than 95.7% of solutions greedy | last-moment-before-all-ants-fall-out-of-a-plank | 0 | 1 | \n# Intuition\nThe first thought I had on how to solve this problem was to find the maximum time taken by the ants to fall off the plank. Since the ants move with a speed of 1 unit per second, the maximum time taken by the ants to fall off the plank is the maximum distance between the ants and the ends of the plank.\n\... | 3 | We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an ... | The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction. |
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥 | last-moment-before-all-ants-fall-out-of-a-plank | 1 | 1 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1 (Easy Traverse)***\n1. We initialize the `ans` variable to 0, which will be used to keep track of the maximum moment when an ant falls off the plank.\n1. We loop through the `left` vector to find the maximum po... | 2 | We have a wooden plank of the length `n` **units**. Some ants are walking on the plank, each ant moves with a speed of **1 unit per second**. Some of the ants move to the **left**, the other move to the **right**.
When two ants moving in two **different** directions meet at some point, they change their directions and... | Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum. If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Ot... |
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥 | last-moment-before-all-ants-fall-out-of-a-plank | 1 | 1 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1 (Easy Traverse)***\n1. We initialize the `ans` variable to 0, which will be used to keep track of the maximum moment when an ant falls off the plank.\n1. We loop through the `left` vector to find the maximum po... | 2 | We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an ... | The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction. |
✅ 91.37% Ants' Behavior & One Line | last-moment-before-all-ants-fall-out-of-a-plank | 1 | 1 | # Intuition\nWhen faced with this problem, the first visualization that comes to mind is ants moving along a line, bouncing back when they meet each other, and eventually falling off the plank. This seems like a dynamic system with multiple interactions. However, upon deeper contemplation, one realizes that the interac... | 34 | We have a wooden plank of the length `n` **units**. Some ants are walking on the plank, each ant moves with a speed of **1 unit per second**. Some of the ants move to the **left**, the other move to the **right**.
When two ants moving in two **different** directions meet at some point, they change their directions and... | Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum. If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Ot... |
✅ 91.37% Ants' Behavior & One Line | last-moment-before-all-ants-fall-out-of-a-plank | 1 | 1 | # Intuition\nWhen faced with this problem, the first visualization that comes to mind is ants moving along a line, bouncing back when they meet each other, and eventually falling off the plank. This seems like a dynamic system with multiple interactions. However, upon deeper contemplation, one realizes that the interac... | 34 | We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an ... | The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction. |
🔥The only shortest 1 line🔥 | last-moment-before-all-ants-fall-out-of-a-plank | 0 | 1 | # Code\n```\nclass Solution:\n def getLastMoment(self, n: int, l: List[int], r: List[int]) -> int:\n return max(l + [n - x for x in r])\n```\nplease upvote :D | 1 | We have a wooden plank of the length `n` **units**. Some ants are walking on the plank, each ant moves with a speed of **1 unit per second**. Some of the ants move to the **left**, the other move to the **right**.
When two ants moving in two **different** directions meet at some point, they change their directions and... | Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum. If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Ot... |
🔥The only shortest 1 line🔥 | last-moment-before-all-ants-fall-out-of-a-plank | 0 | 1 | # Code\n```\nclass Solution:\n def getLastMoment(self, n: int, l: List[int], r: List[int]) -> int:\n return max(l + [n - x for x in r])\n```\nplease upvote :D | 1 | We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an ... | The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction. |
🚀 100% || Easy Iterative Approach || Explained Intuition 🚀 | last-moment-before-all-ants-fall-out-of-a-plank | 1 | 1 | # Problem Description\nYou have a wooden plank of a **specific** length, measured in **units**. On this plank, there are a group of ants moving in **two opposite** directions. Each ant moves at a constant speed of `1 unit per second`. When ants traveling in opposite directions **meet**, they instantaneously **reverse**... | 27 | We have a wooden plank of the length `n` **units**. Some ants are walking on the plank, each ant moves with a speed of **1 unit per second**. Some of the ants move to the **left**, the other move to the **right**.
When two ants moving in two **different** directions meet at some point, they change their directions and... | Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum. If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Ot... |
🚀 100% || Easy Iterative Approach || Explained Intuition 🚀 | last-moment-before-all-ants-fall-out-of-a-plank | 1 | 1 | # Problem Description\nYou have a wooden plank of a **specific** length, measured in **units**. On this plank, there are a group of ants moving in **two opposite** directions. Each ant moves at a constant speed of `1 unit per second`. When ants traveling in opposite directions **meet**, they instantaneously **reverse**... | 27 | We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an ... | The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction. |
Easy peezy lemon squeezy | last-moment-before-all-ants-fall-out-of-a-plank | 0 | 1 | # Intuition\nThe bumping of two ants is a catch here. Actually it doesn\'t matter. When two ants \'collide\' is like they\'re just swapping places. So the ant that is the furthest from the edge is going to be the last to bump and it\'s distance from the edge is the time `t`.\n\n# Approach\nBasically calculate max from ... | 1 | We have a wooden plank of the length `n` **units**. Some ants are walking on the plank, each ant moves with a speed of **1 unit per second**. Some of the ants move to the **left**, the other move to the **right**.
When two ants moving in two **different** directions meet at some point, they change their directions and... | Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum. If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Ot... |
Easy peezy lemon squeezy | last-moment-before-all-ants-fall-out-of-a-plank | 0 | 1 | # Intuition\nThe bumping of two ants is a catch here. Actually it doesn\'t matter. When two ants \'collide\' is like they\'re just swapping places. So the ant that is the furthest from the edge is going to be the last to bump and it\'s distance from the edge is the time `t`.\n\n# Approach\nBasically calculate max from ... | 1 | We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an ... | The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction. |
simple solution just by using max() | last-moment-before-all-ants-fall-out-of-a-plank | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst of all even if they do turn around when they meet it doesn\'t matter because the total number of ants going that way remais the same.\n\nNo position change, no distance changig in between any two ants\nso it doesn\'t matter.\n\nThe ... | 1 | We have a wooden plank of the length `n` **units**. Some ants are walking on the plank, each ant moves with a speed of **1 unit per second**. Some of the ants move to the **left**, the other move to the **right**.
When two ants moving in two **different** directions meet at some point, they change their directions and... | Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum. If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Ot... |
simple solution just by using max() | last-moment-before-all-ants-fall-out-of-a-plank | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst of all even if they do turn around when they meet it doesn\'t matter because the total number of ants going that way remais the same.\n\nNo position change, no distance changig in between any two ants\nso it doesn\'t matter.\n\nThe ... | 1 | We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor **strictly greater** than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an ... | The ants change their way when they meet is equivalent to continue moving without changing their direction. Answer is the max distance for one ant to reach the end of the plank in the facing direction. |
[Python3] O(MN) histogram model | count-submatrices-with-all-ones | 0 | 1 | Algo \nIn the first step, stack `mat` row by row to get the "histogram model". For example, \n```\nmat = [[1,0,1],\n [1,1,0],\n [1,1,0]]\n```\nbecomes \n```\nmat = [[1,0,1],\n [2,1,0],\n [3,2,0]]\n```\nIn the second step, traverse the stacked matrix row by row. At each position `i, j`, compute t... | 124 | Given an `m x n` binary matrix `mat`, _return the number of **submatrices** that have all ones_.
**Example 1:**
**Input:** mat = \[\[1,0,1\],\[1,1,0\],\[1,1,0\]\]
**Output:** 13
**Explanation:**
There are 6 rectangles of side 1x1.
There are 2 rectangles of side 1x2.
There are 3 rectangles of side 2x1.
There is 1 rec... | null |
Without dp, 80% TC and 65% SC easy python solution | count-submatrices-with-all-ones | 0 | 1 | Without dp\n```\ndef numSubmat(self, mat: List[List[int]]) -> int:\n\tm, n = len(mat), len(mat[0])\n\tpref = [[0] for _ in range(m)]\n\tfor i in range(m):\n\t\tfor j in range(n):\n\t\t\tpref[i].append(pref[i][-1] + mat[i][j])\n\tans = 0\n\tfor i in range(n+1):\n\t\tfor j in range(i+1, n+1):\n\t\t\tdiff = j-i\n\t\t\tc =... | 1 | Given an `m x n` binary matrix `mat`, _return the number of **submatrices** that have all ones_.
**Example 1:**
**Input:** mat = \[\[1,0,1\],\[1,1,0\],\[1,1,0\]\]
**Output:** 13
**Explanation:**
There are 6 rectangles of side 1x1.
There are 2 rectangles of side 1x2.
There are 3 rectangles of side 2x1.
There is 1 rec... | null |
Python solution | count-submatrices-with-all-ones | 0 | 1 | loop through each row. use a list to record the height of each column, and a stack to record the height and the # of additional submatrices created by column for each row\n\nif the height of the cur column< that of the previous column in the stack, pop the record of the previous column from the stack until either the ... | 9 | Given an `m x n` binary matrix `mat`, _return the number of **submatrices** that have all ones_.
**Example 1:**
**Input:** mat = \[\[1,0,1\],\[1,1,0\],\[1,1,0\]\]
**Output:** 13
**Explanation:**
There are 6 rectangles of side 1x1.
There are 2 rectangles of side 1x2.
There are 3 rectangles of side 2x1.
There is 1 rec... | null |
Python3 - O(mn) time complexity, using stack | count-submatrices-with-all-ones | 0 | 1 | # Intuition\nThis problem is advanced problem of https://leetcode.com/problems/sum-of-subarray-minimums/\n\n# Approach\n\n\n# Complexity\n- Time complexity: O(mn)\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def numSubmat(self, matrix: List[List[int]]) -> int:\n m = len(matrix)\n n = len... | 0 | Given an `m x n` binary matrix `mat`, _return the number of **submatrices** that have all ones_.
**Example 1:**
**Input:** mat = \[\[1,0,1\],\[1,1,0\],\[1,1,0\]\]
**Output:** 13
**Explanation:**
There are 6 rectangles of side 1x1.
There are 2 rectangles of side 1x2.
There are 3 rectangles of side 2x1.
There is 1 rec... | null |
Power of Monotonic Stack . . . | count-submatrices-with-all-ones | 0 | 1 | \n# Time complexity: $$O(n^3)$$\n\n# Code\n```\nclass Solution:\n def numSubmat(self, mat) -> int:\n res = 0\n for col_limit in range(1, len(mat[0]) + 1):\n for c in range(len(mat[0]) - col_limit + 1):\n length = 1\n for r in range(len(mat)):\n ... | 0 | Given an `m x n` binary matrix `mat`, _return the number of **submatrices** that have all ones_.
**Example 1:**
**Input:** mat = \[\[1,0,1\],\[1,1,0\],\[1,1,0\]\]
**Output:** 13
**Explanation:**
There are 6 rectangles of side 1x1.
There are 2 rectangles of side 1x2.
There are 3 rectangles of side 2x1.
There is 1 rec... | null |
Python (Simple BIT) | minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits | 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 string `num` representing **the digits** of a very large integer and an integer `k`. You are allowed to swap any two adjacent digits of the integer **at most** `k` times.
Return _the minimum integer you can obtain also as a string_.
**Example 1:**
**Input:** num = "4321 ", k = 4
**Output:** "1342 "... | Simulate the process and fill corresponding numbers in the designated spots. |
Python (Simple BIT) | minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits | 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 | A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time.
You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the `ith` key pressed in the testing sequence, and a sorted list `releaseTimes`, where `releaseTimes[i]` was the time the `ith` key was releas... | We want to make the smaller digits the most significant digits in the number. For each index i, check the smallest digit in a window of size k and append it to the answer. Update the indices of all digits in this range accordingly. |
O(NlogN), a SortedList and 10 queues | minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits | 0 | 1 | # Intuition\nIterating from the left, we want to find the smallest reacheable digit and put it on each place.\n\n# Approach\nWe keep 10 queues, containing sequences of indices for each digit. At each step we pick the smallest digit that is not further than `k` steps away. After that we remove it from its queue, and red... | 0 | You are given a string `num` representing **the digits** of a very large integer and an integer `k`. You are allowed to swap any two adjacent digits of the integer **at most** `k` times.
Return _the minimum integer you can obtain also as a string_.
**Example 1:**
**Input:** num = "4321 ", k = 4
**Output:** "1342 "... | Simulate the process and fill corresponding numbers in the designated spots. |
O(NlogN), a SortedList and 10 queues | minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits | 0 | 1 | # Intuition\nIterating from the left, we want to find the smallest reacheable digit and put it on each place.\n\n# Approach\nWe keep 10 queues, containing sequences of indices for each digit. At each step we pick the smallest digit that is not further than `k` steps away. After that we remove it from its queue, and red... | 0 | A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time.
You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the `ith` key pressed in the testing sequence, and a sorted list `releaseTimes`, where `releaseTimes[i]` was the time the `ith` key was releas... | We want to make the smaller digits the most significant digits in the number. For each index i, check the smallest digit in a window of size k and append it to the answer. Update the indices of all digits in this range accordingly. |
Python Sliding Window + AVL Tree Solution | Easy to Understand | minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nMaintain a window of size ```k``` in a AVL Tree, pop out the minimum element in the index in $$O(log(n))$$ time, find its index, decrement ```k``` accordingly until ```k``` becomes ```0```.\n\n# Complexity\n- Time complexity: $$O(n * log(n))$$\n<!-- A... | 0 | You are given a string `num` representing **the digits** of a very large integer and an integer `k`. You are allowed to swap any two adjacent digits of the integer **at most** `k` times.
Return _the minimum integer you can obtain also as a string_.
**Example 1:**
**Input:** num = "4321 ", k = 4
**Output:** "1342 "... | Simulate the process and fill corresponding numbers in the designated spots. |
Python Sliding Window + AVL Tree Solution | Easy to Understand | minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nMaintain a window of size ```k``` in a AVL Tree, pop out the minimum element in the index in $$O(log(n))$$ time, find its index, decrement ```k``` accordingly until ```k``` becomes ```0```.\n\n# Complexity\n- Time complexity: $$O(n * log(n))$$\n<!-- A... | 0 | A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time.
You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the `ith` key pressed in the testing sequence, and a sorted list `releaseTimes`, where `releaseTimes[i]` was the time the `ith` key was releas... | We want to make the smaller digits the most significant digits in the number. For each index i, check the smallest digit in a window of size k and append it to the answer. Update the indices of all digits in this range accordingly. |
[Python3] brute force | minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits | 0 | 1 | Algo\nScan through the string. At each index, look for the smallest element behind it within k swaps. Upon finding such minimum, swap it to replece the current element, and reduce k to reflect the swaps. Do this for all element until k becomes 0. \n\n`O(N^2)` time & `O(N)` space \n```\nclass Solution:\n def minInteg... | 2 | You are given a string `num` representing **the digits** of a very large integer and an integer `k`. You are allowed to swap any two adjacent digits of the integer **at most** `k` times.
Return _the minimum integer you can obtain also as a string_.
**Example 1:**
**Input:** num = "4321 ", k = 4
**Output:** "1342 "... | Simulate the process and fill corresponding numbers in the designated spots. |
[Python3] brute force | minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits | 0 | 1 | Algo\nScan through the string. At each index, look for the smallest element behind it within k swaps. Upon finding such minimum, swap it to replece the current element, and reduce k to reflect the swaps. Do this for all element until k becomes 0. \n\n`O(N^2)` time & `O(N)` space \n```\nclass Solution:\n def minInteg... | 2 | A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time.
You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the `ith` key pressed in the testing sequence, and a sorted list `releaseTimes`, where `releaseTimes[i]` was the time the `ith` key was releas... | We want to make the smaller digits the most significant digits in the number. For each index i, check the smallest digit in a window of size k and append it to the answer. Update the indices of all digits in this range accordingly. |
Simple solution. Beats 97% in Python | reformat-date | 0 | 1 | # Steps:\n1. Split the given string and unpack it into variables.\n2. Cut off the suffix from the day\'s string as long as it will not be needed in the final answer.\n3. If the day value is less than 10, add a zero to the beginning of the string. To do so:\n a. Append zero to the end of the string.\n b. Reverse t... | 0 | Given a `date` string in the form `Day Month Year`, where:
* `Day` is in the set `{ "1st ", "2nd ", "3rd ", "4th ", ..., "30th ", "31st "}`.
* `Month` is in the set `{ "Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec "}`.
* `Year` is in the range `[1900, 2100]`.
Conve... | Start DFS from the node (0, 0) and follow the path till you stop. When you reach a cell and cannot move anymore check that this cell is (m - 1, n - 1) or not. |
Simple solution. Beats 97% in Python | reformat-date | 0 | 1 | # Steps:\n1. Split the given string and unpack it into variables.\n2. Cut off the suffix from the day\'s string as long as it will not be needed in the final answer.\n3. If the day value is less than 10, add a zero to the beginning of the string. To do so:\n a. Append zero to the end of the string.\n b. Reverse t... | 0 | Given an array of integers `nums` and an integer `threshold`, we will choose a positive integer `divisor`, divide all the array by it, and sum the division's result. Find the **smallest** `divisor` such that the result mentioned above is less than or equal to `threshold`.
Each result of the division is rounded to the ... | Handle the conversions of day, month and year separately. Notice that days always have a two-word ending, so if you erase the last two characters of this days you'll get the number. |
Python 3 - Easy Dict. Solution w/out imports (98%) | reformat-date | 0 | 1 | Explanation in comments. Avoided using imports.\n```\nclass Solution:\n def reformatDate(self, date: str) -> str:\n s = date.split() # Divides the elements into 3 individual parts\n \n monthDict = {\'Jan\': \'01\', \'Feb\': \'02\', \n \'Mar\': \'03\', \'Apr\': \'04\', \n ... | 14 | Given a `date` string in the form `Day Month Year`, where:
* `Day` is in the set `{ "1st ", "2nd ", "3rd ", "4th ", ..., "30th ", "31st "}`.
* `Month` is in the set `{ "Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec "}`.
* `Year` is in the range `[1900, 2100]`.
Conve... | Start DFS from the node (0, 0) and follow the path till you stop. When you reach a cell and cannot move anymore check that this cell is (m - 1, n - 1) or not. |
Python 3 - Easy Dict. Solution w/out imports (98%) | reformat-date | 0 | 1 | Explanation in comments. Avoided using imports.\n```\nclass Solution:\n def reformatDate(self, date: str) -> str:\n s = date.split() # Divides the elements into 3 individual parts\n \n monthDict = {\'Jan\': \'01\', \'Feb\': \'02\', \n \'Mar\': \'03\', \'Apr\': \'04\', \n ... | 14 | Given an array of integers `nums` and an integer `threshold`, we will choose a positive integer `divisor`, divide all the array by it, and sum the division's result. Find the **smallest** `divisor` such that the result mentioned above is less than or equal to `threshold`.
Each result of the division is rounded to the ... | Handle the conversions of day, month and year separately. Notice that days always have a two-word ending, so if you erase the last two characters of this days you'll get the number. |
Runtime beats 92.64% of Python | reformat-date | 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)$$ --... | 3 | Given a `date` string in the form `Day Month Year`, where:
* `Day` is in the set `{ "1st ", "2nd ", "3rd ", "4th ", ..., "30th ", "31st "}`.
* `Month` is in the set `{ "Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec "}`.
* `Year` is in the range `[1900, 2100]`.
Conve... | Start DFS from the node (0, 0) and follow the path till you stop. When you reach a cell and cannot move anymore check that this cell is (m - 1, n - 1) or not. |
Runtime beats 92.64% of Python | reformat-date | 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)$$ --... | 3 | Given an array of integers `nums` and an integer `threshold`, we will choose a positive integer `divisor`, divide all the array by it, and sum the division's result. Find the **smallest** `divisor` such that the result mentioned above is less than or equal to `threshold`.
Each result of the division is rounded to the ... | Handle the conversions of day, month and year separately. Notice that days always have a two-word ending, so if you erase the last two characters of this days you'll get the number. |
Python solution with comments | reformat-date | 0 | 1 | ```\nclass Solution:\n def reformatDate(self, date: str) -> str:\n months = {\n \'Jan\' : \'01\',\n \'Feb\' : \'02\',\n \'Mar\' : \'03\',\n \'Apr\' : \'04\',\n \'May\' : \'05\',\n \'Jun\' : \'06\',\n \'Jul\' : \'07\',\n \'... | 3 | Given a `date` string in the form `Day Month Year`, where:
* `Day` is in the set `{ "1st ", "2nd ", "3rd ", "4th ", ..., "30th ", "31st "}`.
* `Month` is in the set `{ "Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec "}`.
* `Year` is in the range `[1900, 2100]`.
Conve... | Start DFS from the node (0, 0) and follow the path till you stop. When you reach a cell and cannot move anymore check that this cell is (m - 1, n - 1) or not. |
Python solution with comments | reformat-date | 0 | 1 | ```\nclass Solution:\n def reformatDate(self, date: str) -> str:\n months = {\n \'Jan\' : \'01\',\n \'Feb\' : \'02\',\n \'Mar\' : \'03\',\n \'Apr\' : \'04\',\n \'May\' : \'05\',\n \'Jun\' : \'06\',\n \'Jul\' : \'07\',\n \'... | 3 | Given an array of integers `nums` and an integer `threshold`, we will choose a positive integer `divisor`, divide all the array by it, and sum the division's result. Find the **smallest** `divisor` such that the result mentioned above is less than or equal to `threshold`.
Each result of the division is rounded to the ... | Handle the conversions of day, month and year separately. Notice that days always have a two-word ending, so if you erase the last two characters of this days you'll get the number. |
One-Liner Python re-sub | reformat-date | 0 | 1 | Easy one-liner using `re.sub(pattern, replace, string)` and `datetime` module:\n```\nfrom datetime import datetime as D\ndef reformatDate(self, date: str) -> str:\n return D.strptime(re.sub(\'rd|nd|th|st|\',\'\',date),\'%d %b %Y\').strftime(\'%Y-%m-%d\')\n```\n\nIf you like my solution please hit the up vote but... | 10 | Given a `date` string in the form `Day Month Year`, where:
* `Day` is in the set `{ "1st ", "2nd ", "3rd ", "4th ", ..., "30th ", "31st "}`.
* `Month` is in the set `{ "Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec "}`.
* `Year` is in the range `[1900, 2100]`.
Conve... | Start DFS from the node (0, 0) and follow the path till you stop. When you reach a cell and cannot move anymore check that this cell is (m - 1, n - 1) or not. |
One-Liner Python re-sub | reformat-date | 0 | 1 | Easy one-liner using `re.sub(pattern, replace, string)` and `datetime` module:\n```\nfrom datetime import datetime as D\ndef reformatDate(self, date: str) -> str:\n return D.strptime(re.sub(\'rd|nd|th|st|\',\'\',date),\'%d %b %Y\').strftime(\'%Y-%m-%d\')\n```\n\nIf you like my solution please hit the up vote but... | 10 | Given an array of integers `nums` and an integer `threshold`, we will choose a positive integer `divisor`, divide all the array by it, and sum the division's result. Find the **smallest** `divisor` such that the result mentioned above is less than or equal to `threshold`.
Each result of the division is rounded to the ... | Handle the conversions of day, month and year separately. Notice that days always have a two-word ending, so if you erase the last two characters of this days you'll get the number. |
Simple Python solution | Constant Time | reformat-date | 0 | 1 | ```\nclass Solution:\n def reformatDate(self, date: str) -> str:\n date = date.split()\n d = {"Jan":"01", "Feb":"02", "Mar":"03", "Apr":"04", "May":"05", "Jun":"06", "Jul":"07", "Aug":"08", "Sep":"09", "Oct":"10", "Nov":"11", "Dec":"12"}\n if int(date[-3][:-2]) < 10:\n date[-3] = "0"+... | 1 | Given a `date` string in the form `Day Month Year`, where:
* `Day` is in the set `{ "1st ", "2nd ", "3rd ", "4th ", ..., "30th ", "31st "}`.
* `Month` is in the set `{ "Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec "}`.
* `Year` is in the range `[1900, 2100]`.
Conve... | Start DFS from the node (0, 0) and follow the path till you stop. When you reach a cell and cannot move anymore check that this cell is (m - 1, n - 1) or not. |
Simple Python solution | Constant Time | reformat-date | 0 | 1 | ```\nclass Solution:\n def reformatDate(self, date: str) -> str:\n date = date.split()\n d = {"Jan":"01", "Feb":"02", "Mar":"03", "Apr":"04", "May":"05", "Jun":"06", "Jul":"07", "Aug":"08", "Sep":"09", "Oct":"10", "Nov":"11", "Dec":"12"}\n if int(date[-3][:-2]) < 10:\n date[-3] = "0"+... | 1 | Given an array of integers `nums` and an integer `threshold`, we will choose a positive integer `divisor`, divide all the array by it, and sum the division's result. Find the **smallest** `divisor` such that the result mentioned above is less than or equal to `threshold`.
Each result of the division is rounded to the ... | Handle the conversions of day, month and year separately. Notice that days always have a two-word ending, so if you erase the last two characters of this days you'll get the number. |
dumb python method | reformat-date | 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 `date` string in the form `Day Month Year`, where:
* `Day` is in the set `{ "1st ", "2nd ", "3rd ", "4th ", ..., "30th ", "31st "}`.
* `Month` is in the set `{ "Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec "}`.
* `Year` is in the range `[1900, 2100]`.
Conve... | Start DFS from the node (0, 0) and follow the path till you stop. When you reach a cell and cannot move anymore check that this cell is (m - 1, n - 1) or not. |
dumb python method | reformat-date | 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 an array of integers `nums` and an integer `threshold`, we will choose a positive integer `divisor`, divide all the array by it, and sum the division's result. Find the **smallest** `divisor` such that the result mentioned above is less than or equal to `threshold`.
Each result of the division is rounded to the ... | Handle the conversions of day, month and year separately. Notice that days always have a two-word ending, so if you erase the last two characters of this days you'll get the number. |
python beats 95% | reformat-date | 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 `date` string in the form `Day Month Year`, where:
* `Day` is in the set `{ "1st ", "2nd ", "3rd ", "4th ", ..., "30th ", "31st "}`.
* `Month` is in the set `{ "Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec "}`.
* `Year` is in the range `[1900, 2100]`.
Conve... | Start DFS from the node (0, 0) and follow the path till you stop. When you reach a cell and cannot move anymore check that this cell is (m - 1, n - 1) or not. |
python beats 95% | reformat-date | 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 an array of integers `nums` and an integer `threshold`, we will choose a positive integer `divisor`, divide all the array by it, and sum the division's result. Find the **smallest** `divisor` such that the result mentioned above is less than or equal to `threshold`.
Each result of the division is rounded to the ... | Handle the conversions of day, month and year separately. Notice that days always have a two-word ending, so if you erase the last two characters of this days you'll get the number. |
Very Easy to understand | reformat-date | 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 `date` string in the form `Day Month Year`, where:
* `Day` is in the set `{ "1st ", "2nd ", "3rd ", "4th ", ..., "30th ", "31st "}`.
* `Month` is in the set `{ "Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec "}`.
* `Year` is in the range `[1900, 2100]`.
Conve... | Start DFS from the node (0, 0) and follow the path till you stop. When you reach a cell and cannot move anymore check that this cell is (m - 1, n - 1) or not. |
Very Easy to understand | reformat-date | 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 an array of integers `nums` and an integer `threshold`, we will choose a positive integer `divisor`, divide all the array by it, and sum the division's result. Find the **smallest** `divisor` such that the result mentioned above is less than or equal to `threshold`.
Each result of the division is rounded to the ... | Handle the conversions of day, month and year separately. Notice that days always have a two-word ending, so if you erase the last two characters of this days you'll get the number. |
[Python3] priority queue | range-sum-of-sorted-subarray-sums | 0 | 1 | Approach 1 (brute force) \nCollect all "range sum" and sort them. Return the sum of numbers between `left` and `right` modulo `1_000_000_007`. \n\n`O(N^2 logN)` time & `O(N^2)` space (376ms)\n```\nclass Solution:\n def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:\n ans = []\n ... | 57 | You are given the array `nums` consisting of `n` positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of `n * (n + 1) / 2` numbers.
_Return the sum of the numbers from index_ `left` _to index_ `right` (**indexed ... | Use Longest Prefix Suffix (KMP-table) or String Hashing. |
[Python3] priority queue | range-sum-of-sorted-subarray-sums | 0 | 1 | Approach 1 (brute force) \nCollect all "range sum" and sort them. Return the sum of numbers between `left` and `right` modulo `1_000_000_007`. \n\n`O(N^2 logN)` time & `O(N^2)` space (376ms)\n```\nclass Solution:\n def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:\n ans = []\n ... | 57 | There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`.
The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either... | Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7. |
BruteForce Solution | range-sum-of-sorted-subarray-sums | 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 the array `nums` consisting of `n` positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of `n * (n + 1) / 2` numbers.
_Return the sum of the numbers from index_ `left` _to index_ `right` (**indexed ... | Use Longest Prefix Suffix (KMP-table) or String Hashing. |
BruteForce Solution | range-sum-of-sorted-subarray-sums | 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 is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`.
The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either... | Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7. |
EASY solution | range-sum-of-sorted-subarray-sums | 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 the array `nums` consisting of `n` positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of `n * (n + 1) / 2` numbers.
_Return the sum of the numbers from index_ `left` _to index_ `right` (**indexed ... | Use Longest Prefix Suffix (KMP-table) or String Hashing. |
EASY solution | range-sum-of-sorted-subarray-sums | 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 is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`.
The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either... | Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7. |
easy python solution | beginner friendly | range-sum-of-sorted-subarray-sums | 0 | 1 | **time complexity of below code is O (n^2 log n) due to the sorting step. To improve the time complexity, we can use a priority queue (min-heap) to keep track of the smallest subarray sums which help in reducing it to O(n^2)**\n\n\n\nclass Solution:\n def rangeSum(self, nums: List[int], n: int, left: int, right: int... | 0 | You are given the array `nums` consisting of `n` positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of `n * (n + 1) / 2` numbers.
_Return the sum of the numbers from index_ `left` _to index_ `right` (**indexed ... | Use Longest Prefix Suffix (KMP-table) or String Hashing. |
easy python solution | beginner friendly | range-sum-of-sorted-subarray-sums | 0 | 1 | **time complexity of below code is O (n^2 log n) due to the sorting step. To improve the time complexity, we can use a priority queue (min-heap) to keep track of the smallest subarray sums which help in reducing it to O(n^2)**\n\n\n\nclass Solution:\n def rangeSum(self, nums: List[int], n: int, left: int, right: int... | 0 | There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`.
The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either... | Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7. |
Python3 Naive Solution , O(N**2) | range-sum-of-sorted-subarray-sums | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:\n \n \n n=len(nums)\n l=[]\n for i in range(n):\n sm=0\n for j in range(i,n):\n sm+=nums[j]\n l.append(sm)\n \n ... | 0 | You are given the array `nums` consisting of `n` positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of `n * (n + 1) / 2` numbers.
_Return the sum of the numbers from index_ `left` _to index_ `right` (**indexed ... | Use Longest Prefix Suffix (KMP-table) or String Hashing. |
Python3 Naive Solution , O(N**2) | range-sum-of-sorted-subarray-sums | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:\n \n \n n=len(nums)\n l=[]\n for i in range(n):\n sm=0\n for j in range(i,n):\n sm+=nums[j]\n l.append(sm)\n \n ... | 0 | There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`.
The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either... | Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7. |
python O(n^2*log(n)) simplest prefix sum solution | range-sum-of-sorted-subarray-sums | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nuse prefix sum to compute the sum of all non-empty continuous subarrays\n\n\n\n# Code\n```\nclass Solution:\n def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:\n prefSum=[0]\n arr=[]\n for ... | 0 | You are given the array `nums` consisting of `n` positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of `n * (n + 1) / 2` numbers.
_Return the sum of the numbers from index_ `left` _to index_ `right` (**indexed ... | Use Longest Prefix Suffix (KMP-table) or String Hashing. |
python O(n^2*log(n)) simplest prefix sum solution | range-sum-of-sorted-subarray-sums | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nuse prefix sum to compute the sum of all non-empty continuous subarrays\n\n\n\n# Code\n```\nclass Solution:\n def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:\n prefSum=[0]\n arr=[]\n for ... | 0 | There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`.
The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either... | Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7. |
Solved using sorting technique (Python3 sol.) | range-sum-of-sorted-subarray-sums | 0 | 1 | First taking the subset sum and storing in result list.\nNext sorting it and getting the sum of it.\nspace complexity = O(N * (N + 1) / 2)\nTime Complexity = O(N^2)\n\n# Code\n```\nclass Solution:\n def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:\n result=[]\n for i in range(... | 0 | You are given the array `nums` consisting of `n` positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of `n * (n + 1) / 2` numbers.
_Return the sum of the numbers from index_ `left` _to index_ `right` (**indexed ... | Use Longest Prefix Suffix (KMP-table) or String Hashing. |
Solved using sorting technique (Python3 sol.) | range-sum-of-sorted-subarray-sums | 0 | 1 | First taking the subset sum and storing in result list.\nNext sorting it and getting the sum of it.\nspace complexity = O(N * (N + 1) / 2)\nTime Complexity = O(N^2)\n\n# Code\n```\nclass Solution:\n def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:\n result=[]\n for i in range(... | 0 | There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`.
The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either... | Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7. |
Python3 || easy understanding || step by step approach || | minimum-difference-between-largest-and-smallest-value-in-three-moves | 0 | 1 | \n"""\n\n\t\t\tclass Solution:\n\t\t\t\n\t\t\t\tdef minDifference(self, nums: List[int]) -> int:\n\t\t\t\t\tn = len(nums)\n\t\t\t\t\tans = math.inf\n\t\t\t\t\tif n<=4:\n\t\t\t\t\t\treturn 0\n\t\t\t\t\tnums.sort... | 1 | You are given an integer array `nums`.
In one move, you can choose one element of `nums` and change it to **any value**.
Return _the minimum difference between the largest and smallest value of `nums` **after performing at most three moves**_.
**Example 1:**
**Input:** nums = \[5,3,2,4\]
**Output:** 0
**Explanation... | null |
Python3 || easy understanding || step by step approach || | minimum-difference-between-largest-and-smallest-value-in-three-moves | 0 | 1 | \n"""\n\n\t\t\tclass Solution:\n\t\t\t\n\t\t\t\tdef minDifference(self, nums: List[int]) -> int:\n\t\t\t\t\tn = len(nums)\n\t\t\t\t\tans = math.inf\n\t\t\t\t\tif n<=4:\n\t\t\t\t\t\treturn 0\n\t\t\t\t\tnums.sort... | 1 | You are given two strings `a` and `b` of the same length. Choose an index and split both strings **at the same index**, splitting `a` into two strings: `aprefix` and `asuffix` where `a = aprefix + asuffix`, and splitting `b` into two strings: `bprefix` and `bsuffix` where `b = bprefix + bsuffix`. Check if `aprefix + bs... | The minimum difference possible is is obtained by removing 3 elements between the 3 smallest and 3 largest values in the array. |
Python, 3 lines, well explained, Greedy O(nlogn) | minimum-difference-between-largest-and-smallest-value-in-three-moves | 0 | 1 | If the size <= 4, then just delete all the elements and either no or one element would be left giving the answer 0.\nelse sort the array\nthere are 4 possibilities now:-\n1. delete 3 elements from left and none from right\n2. delete 2 elements from left and one from right\nand so on.. now just print the minima.\n```\nc... | 77 | You are given an integer array `nums`.
In one move, you can choose one element of `nums` and change it to **any value**.
Return _the minimum difference between the largest and smallest value of `nums` **after performing at most three moves**_.
**Example 1:**
**Input:** nums = \[5,3,2,4\]
**Output:** 0
**Explanation... | null |
Python, 3 lines, well explained, Greedy O(nlogn) | minimum-difference-between-largest-and-smallest-value-in-three-moves | 0 | 1 | If the size <= 4, then just delete all the elements and either no or one element would be left giving the answer 0.\nelse sort the array\nthere are 4 possibilities now:-\n1. delete 3 elements from left and none from right\n2. delete 2 elements from left and one from right\nand so on.. now just print the minima.\n```\nc... | 77 | You are given two strings `a` and `b` of the same length. Choose an index and split both strings **at the same index**, splitting `a` into two strings: `aprefix` and `asuffix` where `a = aprefix + asuffix`, and splitting `b` into two strings: `bprefix` and `bsuffix` where `b = bprefix + bsuffix`. Check if `aprefix + bs... | The minimum difference possible is is obtained by removing 3 elements between the 3 smallest and 3 largest values in the array. |
[Python3/Python] Easy readable solution with comments. | minimum-difference-between-largest-and-smallest-value-in-three-moves | 0 | 1 | ```\nclass Solution:\n \n def minDifference(self, nums: List[int]) -> int:\n \n n = len(nums)\n # If nums are less than 3 all can be replace,\n # so min diff will be 0, which is default condition\n if n > 3:\n \n # Init min difference\n min_diff ... | 10 | You are given an integer array `nums`.
In one move, you can choose one element of `nums` and change it to **any value**.
Return _the minimum difference between the largest and smallest value of `nums` **after performing at most three moves**_.
**Example 1:**
**Input:** nums = \[5,3,2,4\]
**Output:** 0
**Explanation... | null |
[Python3/Python] Easy readable solution with comments. | minimum-difference-between-largest-and-smallest-value-in-three-moves | 0 | 1 | ```\nclass Solution:\n \n def minDifference(self, nums: List[int]) -> int:\n \n n = len(nums)\n # If nums are less than 3 all can be replace,\n # so min diff will be 0, which is default condition\n if n > 3:\n \n # Init min difference\n min_diff ... | 10 | You are given two strings `a` and `b` of the same length. Choose an index and split both strings **at the same index**, splitting `a` into two strings: `aprefix` and `asuffix` where `a = aprefix + asuffix`, and splitting `b` into two strings: `bprefix` and `bsuffix` where `b = bprefix + bsuffix`. Check if `aprefix + bs... | The minimum difference possible is is obtained by removing 3 elements between the 3 smallest and 3 largest values in the array. |
[Python3] 1-line O(N) | minimum-difference-between-largest-and-smallest-value-in-three-moves | 0 | 1 | Algo\nHere, at most 8 numbers are relevant, i.e. the 4 smallest and the 4 largest. Suppose they are labeled as \n\n`m1, m2, m3, m4, ... M4, M3, M2, M1` \n\nthen `min(M4-m1, M3-m2, M2-m3, M1-m4)` gives the solution. It is linear `O(N)` to find `m1-m4` and `M1-M4` like below. \n\n`O(N)` time & `O(1)` space leveraging on ... | 9 | You are given an integer array `nums`.
In one move, you can choose one element of `nums` and change it to **any value**.
Return _the minimum difference between the largest and smallest value of `nums` **after performing at most three moves**_.
**Example 1:**
**Input:** nums = \[5,3,2,4\]
**Output:** 0
**Explanation... | null |
[Python3] 1-line O(N) | minimum-difference-between-largest-and-smallest-value-in-three-moves | 0 | 1 | Algo\nHere, at most 8 numbers are relevant, i.e. the 4 smallest and the 4 largest. Suppose they are labeled as \n\n`m1, m2, m3, m4, ... M4, M3, M2, M1` \n\nthen `min(M4-m1, M3-m2, M2-m3, M1-m4)` gives the solution. It is linear `O(N)` to find `m1-m4` and `M1-M4` like below. \n\n`O(N)` time & `O(1)` space leveraging on ... | 9 | You are given two strings `a` and `b` of the same length. Choose an index and split both strings **at the same index**, splitting `a` into two strings: `aprefix` and `asuffix` where `a = aprefix + asuffix`, and splitting `b` into two strings: `bprefix` and `bsuffix` where `b = bprefix + bsuffix`. Check if `aprefix + bs... | The minimum difference possible is is obtained by removing 3 elements between the 3 smallest and 3 largest values in the array. |
Python short and clean 1-liners. Multiple solutions. Functional programming. | stone-game-iv | 0 | 1 | # Approach 1: Top-Down DP\n\n# Complexity\n- Time complexity: $$O(n \\cdot \\sqrt{n})$$\n\n- Space complexity: $$O(n)$$\n\n# Code\nMultiline Recursive:\n```python\nclass Solution:\n def winnerSquareGame(self, n: int) -> bool:\n squares = lambda x: (i * i for i in range(isqrt(x), 0, -1))\n \n @ca... | 1 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are `n` stones in a pile. On each player's turn, that player makes a _move_ consisting of removing **any** non-zero **square number** of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positi... | Count the frequency of each integer in the array. Get all lucky numbers and return the largest of them. |
Python short and clean 1-liners. Multiple solutions. Functional programming. | stone-game-iv | 0 | 1 | # Approach 1: Top-Down DP\n\n# Complexity\n- Time complexity: $$O(n \\cdot \\sqrt{n})$$\n\n- Space complexity: $$O(n)$$\n\n# Code\nMultiline Recursive:\n```python\nclass Solution:\n def winnerSquareGame(self, n: int) -> bool:\n squares = lambda x: (i * i for i in range(isqrt(x), 0, -1))\n \n @ca... | 1 | There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge between cities `ui` and `vi`. There exists a unique path between each pair of cities. In other words, the cities form a **tree**.
A **subtree** is a subset of cities ... | Use dynamic programming to keep track of winning and losing states. Given some number of stones, Alice can win if she can force Bob onto a losing state. |
✔️ [Python3] JUST 4-LINES, (ノ゚0゚)ノ~ OMG!!!, Explained | stone-game-iv | 0 | 1 | **UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nIn the beginning, it may seem that we would need to do a huge amount of scans, recursive calls and take lots of space doing backtracking since the input `n` is in the range `1..10e5`. But the thing is that a player c... | 11 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are `n` stones in a pile. On each player's turn, that player makes a _move_ consisting of removing **any** non-zero **square number** of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positi... | Count the frequency of each integer in the array. Get all lucky numbers and return the largest of them. |
✔️ [Python3] JUST 4-LINES, (ノ゚0゚)ノ~ OMG!!!, Explained | stone-game-iv | 0 | 1 | **UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nIn the beginning, it may seem that we would need to do a huge amount of scans, recursive calls and take lots of space doing backtracking since the input `n` is in the range `1..10e5`. But the thing is that a player c... | 11 | There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge between cities `ui` and `vi`. There exists a unique path between each pair of cities. In other words, the cities form a **tree**.
A **subtree** is a subset of cities ... | Use dynamic programming to keep track of winning and losing states. Given some number of stones, Alice can win if she can force Bob onto a losing state. |
[Python3] DP | stone-game-iv | 0 | 1 | Below is the code, please let me know if you have any questions!\n```\nclass Solution:\n def winnerSquareGame(self, n: int) -> bool:\n dp = [False] * (n + 1)\n squares = []\n curSquare = 1\n for i in range(1, n + 1):\n if i == curSquare * curSquare:\n squares.app... | 8 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are `n` stones in a pile. On each player's turn, that player makes a _move_ consisting of removing **any** non-zero **square number** of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positi... | Count the frequency of each integer in the array. Get all lucky numbers and return the largest of them. |
[Python3] DP | stone-game-iv | 0 | 1 | Below is the code, please let me know if you have any questions!\n```\nclass Solution:\n def winnerSquareGame(self, n: int) -> bool:\n dp = [False] * (n + 1)\n squares = []\n curSquare = 1\n for i in range(1, n + 1):\n if i == curSquare * curSquare:\n squares.app... | 8 | There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge between cities `ui` and `vi`. There exists a unique path between each pair of cities. In other words, the cities form a **tree**.
A **subtree** is a subset of cities ... | Use dynamic programming to keep track of winning and losing states. Given some number of stones, Alice can win if she can force Bob onto a losing state. |
Standard DP question Explained BEST - ALL you need to know | stone-game-iv | 0 | 1 | We are asked to find the solution for an input of n. So,we find solution for all numbers from [0,n] and we do this because the previous answers help us in finding the solution for a potentially larger number. We have n states of dp,each state represents the solution of that specific state. states = [0,n]. let dp[i] be ... | 8 | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are `n` stones in a pile. On each player's turn, that player makes a _move_ consisting of removing **any** non-zero **square number** of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positi... | Count the frequency of each integer in the array. Get all lucky numbers and return the largest of them. |
Standard DP question Explained BEST - ALL you need to know | stone-game-iv | 0 | 1 | We are asked to find the solution for an input of n. So,we find solution for all numbers from [0,n] and we do this because the previous answers help us in finding the solution for a potentially larger number. We have n states of dp,each state represents the solution of that specific state. states = [0,n]. let dp[i] be ... | 8 | There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge between cities `ui` and `vi`. There exists a unique path between each pair of cities. In other words, the cities form a **tree**.
A **subtree** is a subset of cities ... | Use dynamic programming to keep track of winning and losing states. Given some number of stones, Alice can win if she can force Bob onto a losing state. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.