title stringlengths 1 100 | titleSlug stringlengths 3 77 | Java int64 0 1 | Python3 int64 1 1 | content stringlengths 28 44.4k | voteCount int64 0 3.67k | question_content stringlengths 65 5k | question_hints stringclasses 970
values |
|---|---|---|---|---|---|---|---|
Solution ( 96.51% Faster) | get-maximum-in-generated-array | 0 | 1 | ```\nclass Solution:\n def getMaximumGenerated(self, n: int) -> int:\n l1 = [0,1]\n if n == 2 or n == 1:\n return (1)\n elif n == 0:\n return (0)\n for i in range(1,n):\n l1.append(l1[i])\n if (i * 2) == n:\n break\n l1... | 1 | You are given an integer `n`. A **0-indexed** integer array `nums` of length `n + 1` is generated in the following way:
* `nums[0] = 0`
* `nums[1] = 1`
* `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n`
* `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i + 1 <= n`
Return _the **maximum** integer in the... | Keep track of how many positive numbers are missing as you scan the array. |
Solution ( 96.51% Faster) | get-maximum-in-generated-array | 0 | 1 | ```\nclass Solution:\n def getMaximumGenerated(self, n: int) -> int:\n l1 = [0,1]\n if n == 2 or n == 1:\n return (1)\n elif n == 0:\n return (0)\n for i in range(1,n):\n l1.append(l1[i])\n if (i * 2) == n:\n break\n l1... | 1 | You have `n` boxes. You are given a binary string `boxes` of length `n`, where `boxes[i]` is `'0'` if the `ith` box is **empty**, and `'1'` if it contains **one** ball.
In one operation, you can move **one** ball from a box to an adjacent box. Box `i` is adjacent to box `j` if `abs(i - j) == 1`. Note that after doing ... | Try generating the array. Make sure not to fall in the base case of 0. |
Python 90% Faster Simple Code easy understanding | get-maximum-in-generated-array | 0 | 1 | class Solution:\n def getMaximumGenerated(self, n: int) -> int:\n if n == 0: return 0\n \n nums = [0, 1]\n for i in range(2, n+1):\n if i % 2 == 0:\n nums.append(nums[i//2])\n else:\n nums.append(nums[(i-1)//2]+ nums[(i+1)//2])\n ... | 1 | You are given an integer `n`. A **0-indexed** integer array `nums` of length `n + 1` is generated in the following way:
* `nums[0] = 0`
* `nums[1] = 1`
* `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n`
* `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i + 1 <= n`
Return _the **maximum** integer in the... | Keep track of how many positive numbers are missing as you scan the array. |
Python 90% Faster Simple Code easy understanding | get-maximum-in-generated-array | 0 | 1 | class Solution:\n def getMaximumGenerated(self, n: int) -> int:\n if n == 0: return 0\n \n nums = [0, 1]\n for i in range(2, n+1):\n if i % 2 == 0:\n nums.append(nums[i//2])\n else:\n nums.append(nums[(i-1)//2]+ nums[(i+1)//2])\n ... | 1 | You have `n` boxes. You are given a binary string `boxes` of length `n`, where `boxes[i]` is `'0'` if the `ith` box is **empty**, and `'1'` if it contains **one** ball.
In one operation, you can move **one** ball from a box to an adjacent box. Box `i` is adjacent to box `j` if `abs(i - j) == 1`. Note that after doing ... | Try generating the array. Make sure not to fall in the base case of 0. |
Python3 | 98.24% | Greedy Approach | Easy to Understand | minimum-deletions-to-make-character-frequencies-unique | 0 | 1 | # Python3 | 98.24% | Greedy Approach | Easy to Understand\n```\nclass Solution:\n def minDeletions(self, s: str) -> int:\n cnt = Counter(s)\n deletions = 0\n used_frequencies = set()\n \n for char, freq in cnt.items():\n while freq > 0 and freq in used_frequencies:\n ... | 22 | A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**.
Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._
The **frequency** of a character in a string is the number of times it appears in the string. F... | Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26. |
Python3 | 98.24% | Greedy Approach | Easy to Understand | minimum-deletions-to-make-character-frequencies-unique | 0 | 1 | # Python3 | 98.24% | Greedy Approach | Easy to Understand\n```\nclass Solution:\n def minDeletions(self, s: str) -> int:\n cnt = Counter(s)\n deletions = 0\n used_frequencies = set()\n \n for char, freq in cnt.items():\n while freq > 0 and freq in used_frequencies:\n ... | 22 | You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of t... | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it re... |
Simple Approach Using SortedDict | minimum-deletions-to-make-character-frequencies-unique | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$.\n\n- Space complexity: $$O(1)$$.\n\n# Code\n```\nfrom sortedcontainers import SortedDict\n\nclass Solution:\n def minDeletions(self, s: str) -> int:\n freqToCnt = SortedDict(Counter(Counter(s).values()))\n deletions = 0\n i = -1\n while i >= -len... | 4 | A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**.
Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._
The **frequency** of a character in a string is the number of times it appears in the string. F... | Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26. |
Simple Approach Using SortedDict | minimum-deletions-to-make-character-frequencies-unique | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$.\n\n- Space complexity: $$O(1)$$.\n\n# Code\n```\nfrom sortedcontainers import SortedDict\n\nclass Solution:\n def minDeletions(self, s: str) -> int:\n freqToCnt = SortedDict(Counter(Counter(s).values()))\n deletions = 0\n i = -1\n while i >= -len... | 4 | You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of t... | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it re... |
O(n) Time, O(1) Space Solution - Python, JavaScript, Java, C++ | minimum-deletions-to-make-character-frequencies-unique | 1 | 1 | # Intuition\nUsing HashMap to count each character and Set to keep unique frequency of chracters.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/2CXjNZa0ldo\n\nMinor update:\nIn the video, I use Set and variable name is "uniq_set". It\'s a little bit weird because values in Set are usually unique, so we should use vari... | 33 | A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**.
Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._
The **frequency** of a character in a string is the number of times it appears in the string. F... | Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26. |
O(n) Time, O(1) Space Solution - Python, JavaScript, Java, C++ | minimum-deletions-to-make-character-frequencies-unique | 1 | 1 | # Intuition\nUsing HashMap to count each character and Set to keep unique frequency of chracters.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/2CXjNZa0ldo\n\nMinor update:\nIn the video, I use Set and variable name is "uniq_set". It\'s a little bit weird because values in Set are usually unique, so we should use vari... | 33 | You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of t... | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it re... |
[ Python / Java / C++] 🔥100% | ✅ MAP | minimum-deletions-to-make-character-frequencies-unique | 1 | 1 | ```Python []\nclass Solution:\n def minDeletions(self, s: str) -> int:\n counts=Counter(s)\n res=0\n set1=set()\n for i in counts:\n frec=counts[i]\n if frec in set1:\n while frec in set1 and frec>0: \n frec-=1\n ... | 3 | A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**.
Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._
The **frequency** of a character in a string is the number of times it appears in the string. F... | Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26. |
[ Python / Java / C++] 🔥100% | ✅ MAP | minimum-deletions-to-make-character-frequencies-unique | 1 | 1 | ```Python []\nclass Solution:\n def minDeletions(self, s: str) -> int:\n counts=Counter(s)\n res=0\n set1=set()\n for i in counts:\n frec=counts[i]\n if frec in set1:\n while frec in set1 and frec>0: \n frec-=1\n ... | 3 | You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of t... | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it re... |
✅ 98.18% Greedy & Heap & Sorting | minimum-deletions-to-make-character-frequencies-unique | 1 | 1 | # Comprehensive Guide to Solving "Minimum Deletions to Make Character Frequencies Unique"\n\n## Introduction & Problem Statement\n\nWelcome, code enthusiasts! Today, we\'re tackling an intriguing problem: **Minimum Deletions to Make Character Frequencies Unique**. Given a string `s` , the goal is to delete the minimum... | 106 | A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**.
Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._
The **frequency** of a character in a string is the number of times it appears in the string. F... | Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26. |
✅ 98.18% Greedy & Heap & Sorting | minimum-deletions-to-make-character-frequencies-unique | 1 | 1 | # Comprehensive Guide to Solving "Minimum Deletions to Make Character Frequencies Unique"\n\n## Introduction & Problem Statement\n\nWelcome, code enthusiasts! Today, we\'re tackling an intriguing problem: **Minimum Deletions to Make Character Frequencies Unique**. Given a string `s` , the goal is to delete the minimum... | 106 | You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of t... | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it re... |
Simplest Python solution. Counter + check for values | minimum-deletions-to-make-character-frequencies-unique | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def minDeletions(self, s: str) -> int:\n d = Counter(s)\n ans = 0\n seen = set()\n for k, v in d.items():\n while v and v in seen:\n ans += 1\n v -= 1\n seen.add(v)\n return ans\n``` | 5 | A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**.
Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._
The **frequency** of a character in a string is the number of times it appears in the string. F... | Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26. |
Simplest Python solution. Counter + check for values | minimum-deletions-to-make-character-frequencies-unique | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def minDeletions(self, s: str) -> int:\n d = Counter(s)\n ans = 0\n seen = set()\n for k, v in d.items():\n while v and v in seen:\n ans += 1\n v -= 1\n seen.add(v)\n return ans\n``` | 5 | You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of t... | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it re... |
✅99.32%☑️Greedy+Heap|🔥|Beginner Friendly✅☑️||Full Explanation🔥||C++||Java||Python✅☑️ | minimum-deletions-to-make-character-frequencies-unique | 1 | 1 | # Problem Understanding\nThe given problem **asks you to find the minimum number of characters you need to delete from a string s to make it "good."** A string is **considered "good" if there are no two different characters in it that have the same frequency.**\n# Intuition\n<!-- Describe your first thoughts on how to ... | 189 | A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**.
Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._
The **frequency** of a character in a string is the number of times it appears in the string. F... | Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26. |
✅99.32%☑️Greedy+Heap|🔥|Beginner Friendly✅☑️||Full Explanation🔥||C++||Java||Python✅☑️ | minimum-deletions-to-make-character-frequencies-unique | 1 | 1 | # Problem Understanding\nThe given problem **asks you to find the minimum number of characters you need to delete from a string s to make it "good."** A string is **considered "good" if there are no two different characters in it that have the same frequency.**\n# Intuition\n<!-- Describe your first thoughts on how to ... | 189 | You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of t... | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it re... |
No Priority Queue, No Heap, No Sorting! 10 Liner Solution using hashmap and counters! | minimum-deletions-to-make-character-frequencies-unique | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor each letter check if a previous letter has the same count. If Yes? Keep on decreasing until we get a unique count (we might even make it 0 i.e. delete that letter altogether!)\n\n you will:
* Choose one integer `x` from **either the start or the end** of t... | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it re... |
Minimum Deletions to Make Character Frequencies Unique Java Python and CPP | minimum-deletions-to-make-character-frequencies-unique | 1 | 1 | # Intuition\nThe problem seems to be about finding the minimum number of deletions required to make all characters in the given string appear with unique frequencies. To do this, we can keep track of the frequency of each character and then iteratively check and possibly reduce the frequency of characters until all fre... | 1 | A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**.
Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._
The **frequency** of a character in a string is the number of times it appears in the string. F... | Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26. |
Minimum Deletions to Make Character Frequencies Unique Java Python and CPP | minimum-deletions-to-make-character-frequencies-unique | 1 | 1 | # Intuition\nThe problem seems to be about finding the minimum number of deletions required to make all characters in the given string appear with unique frequencies. To do this, we can keep track of the frequency of each character and then iteratively check and possibly reduce the frequency of characters until all fre... | 1 | You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of t... | As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it re... |
✔ Python3 Solution | Sorting | O(nlogn) | sell-diminishing-valued-colored-balls | 0 | 1 | # Complexity\n- Time complexity: $$O(nlogn)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def maxProfit(self, A, O):\n nsum = lambda n : (n * (n + 1)) // 2\n A.sort(reverse = True)\n A.append(0)\n ans, mod = 0, 10 ** 9 + 7\n for i in range(len(A) - 1):\n ... | 1 | You have an `inventory` of different colored balls, and there is a customer that wants `orders` balls of **any** color.
The customer weirdly values the colored balls. Each colored ball's value is the number of balls **of that color** you currently have in your `inventory`. For example, if you own `6` yellow balls, the... | Use a stack to keep opening brackets. If you face single closing ')' add 1 to the answer and consider it as '))'. If you have '))' with empty stack, add 1 to the answer, If after finishing you have x opening remaining in the stack, add 2x to the answer. |
✔ Python3 Solution | Sorting | O(nlogn) | sell-diminishing-valued-colored-balls | 0 | 1 | # Complexity\n- Time complexity: $$O(nlogn)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def maxProfit(self, A, O):\n nsum = lambda n : (n * (n + 1)) // 2\n A.sort(reverse = True)\n A.append(0)\n ans, mod = 0, 10 ** 9 + 7\n for i in range(len(A) - 1):\n ... | 1 | You are given two strings, `word1` and `word2`. You want to construct a string in the following manner:
* Choose some **non-empty** subsequence `subsequence1` from `word1`.
* Choose some **non-empty** subsequence `subsequence2` from `word2`.
* Concatenate the subsequences: `subsequence1 + subsequence2`, to make ... | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. |
[Python3] Greedy | sell-diminishing-valued-colored-balls | 0 | 1 | Algo \nFirst, it should be clear that we want to sell from the most abundant balls as much as possible as it is valued more than less abundant balls. In the spirit of this, we propose the below algo \n1) sort inventory in reverse order and append 0 at the end (for termination); \n2) scan through the inventory, and add ... | 36 | You have an `inventory` of different colored balls, and there is a customer that wants `orders` balls of **any** color.
The customer weirdly values the colored balls. Each colored ball's value is the number of balls **of that color** you currently have in your `inventory`. For example, if you own `6` yellow balls, the... | Use a stack to keep opening brackets. If you face single closing ')' add 1 to the answer and consider it as '))'. If you have '))' with empty stack, add 1 to the answer, If after finishing you have x opening remaining in the stack, add 2x to the answer. |
[Python3] Greedy | sell-diminishing-valued-colored-balls | 0 | 1 | Algo \nFirst, it should be clear that we want to sell from the most abundant balls as much as possible as it is valued more than less abundant balls. In the spirit of this, we propose the below algo \n1) sort inventory in reverse order and append 0 at the end (for termination); \n2) scan through the inventory, and add ... | 36 | You are given two strings, `word1` and `word2`. You want to construct a string in the following manner:
* Choose some **non-empty** subsequence `subsequence1` from `word1`.
* Choose some **non-empty** subsequence `subsequence2` from `word2`.
* Concatenate the subsequences: `subsequence1 + subsequence2`, to make ... | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. |
85% TC and 84% SC easy python solution | sell-diminishing-valued-colored-balls | 0 | 1 | ```\ndef maxProfit(self, inventory: List[int], orders: int) -> int:\n\tinventory.sort()\n\ti, j = 1, inventory[-1]\n\tans = -1\n\tdef isValid(v):\n\t\tt = orders\n\t\tm = bisect_left(inventory, v)\n\t\tfor i in range(m, len(inventory)):\n\t\t\tt -= inventory[i] - v\n\t\t\tif(t <= 0):\n\t\t\t\treturn 1\n\t\tif(t <= len(... | 1 | You have an `inventory` of different colored balls, and there is a customer that wants `orders` balls of **any** color.
The customer weirdly values the colored balls. Each colored ball's value is the number of balls **of that color** you currently have in your `inventory`. For example, if you own `6` yellow balls, the... | Use a stack to keep opening brackets. If you face single closing ')' add 1 to the answer and consider it as '))'. If you have '))' with empty stack, add 1 to the answer, If after finishing you have x opening remaining in the stack, add 2x to the answer. |
85% TC and 84% SC easy python solution | sell-diminishing-valued-colored-balls | 0 | 1 | ```\ndef maxProfit(self, inventory: List[int], orders: int) -> int:\n\tinventory.sort()\n\ti, j = 1, inventory[-1]\n\tans = -1\n\tdef isValid(v):\n\t\tt = orders\n\t\tm = bisect_left(inventory, v)\n\t\tfor i in range(m, len(inventory)):\n\t\t\tt -= inventory[i] - v\n\t\t\tif(t <= 0):\n\t\t\t\treturn 1\n\t\tif(t <= len(... | 1 | You are given two strings, `word1` and `word2`. You want to construct a string in the following manner:
* Choose some **non-empty** subsequence `subsequence1` from `word1`.
* Choose some **non-empty** subsequence `subsequence2` from `word2`.
* Concatenate the subsequences: `subsequence1 + subsequence2`, to make ... | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. |
Binary search | sell-diminishing-valued-colored-balls | 0 | 1 | ```\nclass Solution:\n def maxProfit(self, inventory, orders: int) -> int:\n left = 0\n right = max(inventory)\n while right - left > 1:\n middle = (left + right) // 2\n sold_balls = sum(i - middle for i in inventory if i > middle)\n if sold_balls > orders:\n ... | 14 | You have an `inventory` of different colored balls, and there is a customer that wants `orders` balls of **any** color.
The customer weirdly values the colored balls. Each colored ball's value is the number of balls **of that color** you currently have in your `inventory`. For example, if you own `6` yellow balls, the... | Use a stack to keep opening brackets. If you face single closing ')' add 1 to the answer and consider it as '))'. If you have '))' with empty stack, add 1 to the answer, If after finishing you have x opening remaining in the stack, add 2x to the answer. |
Binary search | sell-diminishing-valued-colored-balls | 0 | 1 | ```\nclass Solution:\n def maxProfit(self, inventory, orders: int) -> int:\n left = 0\n right = max(inventory)\n while right - left > 1:\n middle = (left + right) // 2\n sold_balls = sum(i - middle for i in inventory if i > middle)\n if sold_balls > orders:\n ... | 14 | You are given two strings, `word1` and `word2`. You want to construct a string in the following manner:
* Choose some **non-empty** subsequence `subsequence1` from `word1`.
* Choose some **non-empty** subsequence `subsequence2` from `word2`.
* Concatenate the subsequences: `subsequence1 + subsequence2`, to make ... | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. |
find error | sell-diminishing-valued-colored-balls | 0 | 1 | can anybody help me to find my mistake?? why my answer is not right\n# Code\n```\nclass Solution:\n def maxProfit(self, inventory: List[int], orders: int) -> int:\n res = 0\n sorted(inventory)\n while orders>0:\n for i in range(len(inventory)):\n while inventory[i]>1:\n... | 0 | You have an `inventory` of different colored balls, and there is a customer that wants `orders` balls of **any** color.
The customer weirdly values the colored balls. Each colored ball's value is the number of balls **of that color** you currently have in your `inventory`. For example, if you own `6` yellow balls, the... | Use a stack to keep opening brackets. If you face single closing ')' add 1 to the answer and consider it as '))'. If you have '))' with empty stack, add 1 to the answer, If after finishing you have x opening remaining in the stack, add 2x to the answer. |
find error | sell-diminishing-valued-colored-balls | 0 | 1 | can anybody help me to find my mistake?? why my answer is not right\n# Code\n```\nclass Solution:\n def maxProfit(self, inventory: List[int], orders: int) -> int:\n res = 0\n sorted(inventory)\n while orders>0:\n for i in range(len(inventory)):\n while inventory[i]>1:\n... | 0 | You are given two strings, `word1` and `word2`. You want to construct a string in the following manner:
* Choose some **non-empty** subsequence `subsequence1` from `word1`.
* Choose some **non-empty** subsequence `subsequence2` from `word2`.
* Concatenate the subsequences: `subsequence1 + subsequence2`, to make ... | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. |
[Python3] Heap 680 ms | sell-diminishing-valued-colored-balls | 0 | 1 | ```py3\nclass Solution:\n def maxProfit(self, h: List[int], orders: int) -> int:\n MOD = int(1e9 + 7)\n def series_sum_length(b, i):\n a = b - (i - 1)\n a_quotient, a_remainder = divmod(a * i, 2)\n b_quotient, b_remainder = divmod(b * i, 2)\n result = (a_quot... | 0 | You have an `inventory` of different colored balls, and there is a customer that wants `orders` balls of **any** color.
The customer weirdly values the colored balls. Each colored ball's value is the number of balls **of that color** you currently have in your `inventory`. For example, if you own `6` yellow balls, the... | Use a stack to keep opening brackets. If you face single closing ')' add 1 to the answer and consider it as '))'. If you have '))' with empty stack, add 1 to the answer, If after finishing you have x opening remaining in the stack, add 2x to the answer. |
[Python3] Heap 680 ms | sell-diminishing-valued-colored-balls | 0 | 1 | ```py3\nclass Solution:\n def maxProfit(self, h: List[int], orders: int) -> int:\n MOD = int(1e9 + 7)\n def series_sum_length(b, i):\n a = b - (i - 1)\n a_quotient, a_remainder = divmod(a * i, 2)\n b_quotient, b_remainder = divmod(b * i, 2)\n result = (a_quot... | 0 | You are given two strings, `word1` and `word2`. You want to construct a string in the following manner:
* Choose some **non-empty** subsequence `subsequence1` from `word1`.
* Choose some **non-empty** subsequence `subsequence2` from `word2`.
* Concatenate the subsequences: `subsequence1 + subsequence2`, to make ... | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. |
[Python] Greedy & Math | sell-diminishing-valued-colored-balls | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def maxProfit(self, inventory: List[int], orders: int) -> int:\n inv, curOrders, curSum, MOD = sorted(inventory, reverse=True) + [0], 0, 0, 1000000007\n for i in range(1, len(inv)):\n if inv[i - 1] == inv[i]: continue\n increments = i * (inv[i - ... | 0 | You have an `inventory` of different colored balls, and there is a customer that wants `orders` balls of **any** color.
The customer weirdly values the colored balls. Each colored ball's value is the number of balls **of that color** you currently have in your `inventory`. For example, if you own `6` yellow balls, the... | Use a stack to keep opening brackets. If you face single closing ')' add 1 to the answer and consider it as '))'. If you have '))' with empty stack, add 1 to the answer, If after finishing you have x opening remaining in the stack, add 2x to the answer. |
[Python] Greedy & Math | sell-diminishing-valued-colored-balls | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def maxProfit(self, inventory: List[int], orders: int) -> int:\n inv, curOrders, curSum, MOD = sorted(inventory, reverse=True) + [0], 0, 0, 1000000007\n for i in range(1, len(inv)):\n if inv[i - 1] == inv[i]: continue\n increments = i * (inv[i - ... | 0 | You are given two strings, `word1` and `word2`. You want to construct a string in the following manner:
* Choose some **non-empty** subsequence `subsequence1` from `word1`.
* Choose some **non-empty** subsequence `subsequence2` from `word2`.
* Concatenate the subsequences: `subsequence1 + subsequence2`, to make ... | Greedily sell the most expensive ball. There is some value k where all balls of value > k are sold, and some, (maybe 0) of balls of value k are sold. Use binary search to find this value k, and use maths to find the total sum. |
python3 SortedList Soultion in O(nlogn) | create-sorted-array-through-instructions | 0 | 1 | ```\nfrom sortedcontainers import SortedList\nclass Solution:\n def createSortedArray(self, ins: List[int]) -> int:\n mod = 10**9+7\n dicti = defaultdict(int)\n s1 = SortedList()\n sum_ = 0\n \n for i in range(len(ins)):\n dicti[ins[i]] += 1\n s1.add(in... | 6 | Given an integer array `instructions`, you are asked to create a sorted array from the elements in `instructions`. You start with an empty container `nums`. For each element from **left to right** in `instructions`, insert it into `nums`. The **cost** of each insertion is the **minimum** of the following:
* The numb... | Keep track of prefix sums to quickly look up what subarray that sums "target" can be formed at each step of scanning the input array. It can be proved that greedily forming valid subarrays as soon as one is found is optimal. |
python3 SortedList Soultion in O(nlogn) | create-sorted-array-through-instructions | 0 | 1 | ```\nfrom sortedcontainers import SortedList\nclass Solution:\n def createSortedArray(self, ins: List[int]) -> int:\n mod = 10**9+7\n dicti = defaultdict(int)\n s1 = SortedList()\n sum_ = 0\n \n for i in range(len(ins)):\n dicti[ins[i]] += 1\n s1.add(in... | 6 | You are given a string array `features` where `features[i]` is a single word that represents the name of a feature of the latest product you are working on. You have made a survey where users have reported which features they like. You are given a string array `responses`, where each `responses[i]` is a string containi... | This problem is closely related to finding the number of inversions in an array if i know the position in which i will insert the i-th element in I can find the minimum cost to insert it |
With python sortedlist all problems like this shall be categorized as easy... | create-sorted-array-through-instructions | 0 | 1 | ```\nfrom sortedcontainers import SortedList\nclass Solution:\n def createSortedArray(self, instructions: List[int]) -> int:\n res = 0\n sl = SortedList([])\n for n in instructions:\n i = sl.bisect_left(n)\n j = sl.bisect_right(n)\n a = len(sl)\n res +... | 0 | Given an integer array `instructions`, you are asked to create a sorted array from the elements in `instructions`. You start with an empty container `nums`. For each element from **left to right** in `instructions`, insert it into `nums`. The **cost** of each insertion is the **minimum** of the following:
* The numb... | Keep track of prefix sums to quickly look up what subarray that sums "target" can be formed at each step of scanning the input array. It can be proved that greedily forming valid subarrays as soon as one is found is optimal. |
With python sortedlist all problems like this shall be categorized as easy... | create-sorted-array-through-instructions | 0 | 1 | ```\nfrom sortedcontainers import SortedList\nclass Solution:\n def createSortedArray(self, instructions: List[int]) -> int:\n res = 0\n sl = SortedList([])\n for n in instructions:\n i = sl.bisect_left(n)\n j = sl.bisect_right(n)\n a = len(sl)\n res +... | 0 | You are given a string array `features` where `features[i]` is a single word that represents the name of a feature of the latest product you are working on. You have made a survey where users have reported which features they like. You are given a string array `responses`, where each `responses[i]` is a string containi... | This problem is closely related to finding the number of inversions in an array if i know the position in which i will insert the i-th element in I can find the minimum cost to insert it |
python3 segment tree | create-sorted-array-through-instructions | 0 | 1 | \n# Code\n```\nimport bisect\n\nclass SegmentTree:\n def __init__(self,arr):\n self.arr = arr\n self.n = len(arr)\n self.tree = [0] * (2 * self.n)\n self.build(self.arr)\n\n def build(self,arr):\n for i in range(self.n):\n self.tree[self.n + i] = arr[i]\n for i... | 0 | Given an integer array `instructions`, you are asked to create a sorted array from the elements in `instructions`. You start with an empty container `nums`. For each element from **left to right** in `instructions`, insert it into `nums`. The **cost** of each insertion is the **minimum** of the following:
* The numb... | Keep track of prefix sums to quickly look up what subarray that sums "target" can be formed at each step of scanning the input array. It can be proved that greedily forming valid subarrays as soon as one is found is optimal. |
python3 segment tree | create-sorted-array-through-instructions | 0 | 1 | \n# Code\n```\nimport bisect\n\nclass SegmentTree:\n def __init__(self,arr):\n self.arr = arr\n self.n = len(arr)\n self.tree = [0] * (2 * self.n)\n self.build(self.arr)\n\n def build(self,arr):\n for i in range(self.n):\n self.tree[self.n + i] = arr[i]\n for i... | 0 | You are given a string array `features` where `features[i]` is a single word that represents the name of a feature of the latest product you are working on. You have made a survey where users have reported which features they like. You are given a string array `responses`, where each `responses[i]` is a string containi... | This problem is closely related to finding the number of inversions in an array if i know the position in which i will insert the i-th element in I can find the minimum cost to insert it |
Python (Simple Segment Tree) | create-sorted-array-through-instructions | 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 integer array `instructions`, you are asked to create a sorted array from the elements in `instructions`. You start with an empty container `nums`. For each element from **left to right** in `instructions`, insert it into `nums`. The **cost** of each insertion is the **minimum** of the following:
* The numb... | Keep track of prefix sums to quickly look up what subarray that sums "target" can be formed at each step of scanning the input array. It can be proved that greedily forming valid subarrays as soon as one is found is optimal. |
Python (Simple Segment Tree) | create-sorted-array-through-instructions | 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 array `features` where `features[i]` is a single word that represents the name of a feature of the latest product you are working on. You have made a survey where users have reported which features they like. You are given a string array `responses`, where each `responses[i]` is a string containi... | This problem is closely related to finding the number of inversions in an array if i know the position in which i will insert the i-th element in I can find the minimum cost to insert it |
Python Easy Solution | defuse-the-bomb | 0 | 1 | # Code\n```\nclass Solution:\n def decrypt(self, code: List[int], k: int) -> List[int]:\n res=[]\n if k>0: \n first=sum(code[:k])\n for i in range(len(code)):\n first=first-code[i]+code[(k+i)%(len(code))]\n res.append(first)\n elif k<0:\n... | 1 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
Python Easy Solution | defuse-the-bomb | 0 | 1 | # Code\n```\nclass Solution:\n def decrypt(self, code: List[int], k: int) -> List[int]:\n res=[]\n if k>0: \n first=sum(code[:k])\n for i in range(len(code)):\n first=first-code[i]+code[(k+i)%(len(code))]\n res.append(first)\n elif k<0:\n... | 1 | You are given an integer array `nums` and an integer `goal`.
You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to **minimize the absolute difference** `abs(sum - goal)`.
Return _the ... | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. |
Easy Python Solution | defuse-the-bomb | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
Easy Python Solution | defuse-the-bomb | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You are given an integer array `nums` and an integer `goal`.
You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to **minimize the absolute difference** `abs(sum - goal)`.
Return _the ... | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. |
Python 3 - O(n) - sliding window with array rotation | defuse-the-bomb | 0 | 1 | # Intuition\nOn close inspection we find that K<0 case solution is just a rotated form of K>0 solution\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nReturn 0 array for k==0 case and for other case find the next k sum array by sliding window technique and in case the k value is nega... | 2 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
Python 3 - O(n) - sliding window with array rotation | defuse-the-bomb | 0 | 1 | # Intuition\nOn close inspection we find that K<0 case solution is just a rotated form of K>0 solution\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nReturn 0 array for k==0 case and for other case find the next k sum array by sliding window technique and in case the k value is nega... | 2 | You are given an integer array `nums` and an integer `goal`.
You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to **minimize the absolute difference** `abs(sum - goal)`.
Return _the ... | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. |
Pyhton3, beats 100%, double the code array | defuse-the-bomb | 0 | 1 | Double the ```code``` array so that it\'s easy to iterate.\n```class Solution:\n def decrypt(self, code: List[int], k: int) -> List[int]:\n if k==0: return [0 for i in code]\n temp = code\n code = code*2\n for i in range(len(temp)):\n if k>0:\n temp[i] = sum(code... | 20 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
Pyhton3, beats 100%, double the code array | defuse-the-bomb | 0 | 1 | Double the ```code``` array so that it\'s easy to iterate.\n```class Solution:\n def decrypt(self, code: List[int], k: int) -> List[int]:\n if k==0: return [0 for i in code]\n temp = code\n code = code*2\n for i in range(len(temp)):\n if k>0:\n temp[i] = sum(code... | 20 | You are given an integer array `nums` and an integer `goal`.
You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to **minimize the absolute difference** `abs(sum - goal)`.
Return _the ... | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. |
simple list slicing and loop process that beats 100% | defuse-the-bomb | 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# **O**(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $... | 2 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
simple list slicing and loop process that beats 100% | defuse-the-bomb | 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# **O**(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $... | 2 | You are given an integer array `nums` and an integer `goal`.
You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to **minimize the absolute difference** `abs(sum - goal)`.
Return _the ... | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. |
simple and easy | defuse-the-bomb | 0 | 1 | ```\noutput = []\nfor i in range(len(code)):\n\tif k > 0:\n\t\tsum = 0\n\t\tj = i+1\n\t\tm = k\n\t\twhile(m):\n\t\t\tsum+=code[j%len(code)]\n\t\t\tm-=1\n\t\t\tj+=1\n\t\toutput.append(sum)\n\n\telif k == 0:\n\t\toutput.append(0)\n\n\telse:\n\t\tsum = 0\n\t\tj = i-1\n\t\tm = k\n\t\twhile(m):\n\t\t\tsum+=code[j%len(code)]... | 7 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
simple and easy | defuse-the-bomb | 0 | 1 | ```\noutput = []\nfor i in range(len(code)):\n\tif k > 0:\n\t\tsum = 0\n\t\tj = i+1\n\t\tm = k\n\t\twhile(m):\n\t\t\tsum+=code[j%len(code)]\n\t\t\tm-=1\n\t\t\tj+=1\n\t\toutput.append(sum)\n\n\telif k == 0:\n\t\toutput.append(0)\n\n\telse:\n\t\tsum = 0\n\t\tj = i-1\n\t\tm = k\n\t\twhile(m):\n\t\t\tsum+=code[j%len(code)]... | 7 | You are given an integer array `nums` and an integer `goal`.
You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to **minimize the absolute difference** `abs(sum - goal)`.
Return _the ... | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. |
Python Solution | defuse-the-bomb | 0 | 1 | ```python\nclass Solution:\n def decrypt(self, code: List[int], k: int) -> List[int]:\n if k == 0:\n return [0] * len(code)\n data = code + code\n result = [sum(data[i + 1: i + 1 + abs(k)]) for i in range(len(code))]\n\t\t# result = []\n # for i in range(len(code)):\n # ... | 3 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
Python Solution | defuse-the-bomb | 0 | 1 | ```python\nclass Solution:\n def decrypt(self, code: List[int], k: int) -> List[int]:\n if k == 0:\n return [0] * len(code)\n data = code + code\n result = [sum(data[i + 1: i + 1 + abs(k)]) for i in range(len(code))]\n\t\t# result = []\n # for i in range(len(code)):\n # ... | 3 | You are given an integer array `nums` and an integer `goal`.
You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to **minimize the absolute difference** `abs(sum - goal)`.
Return _the ... | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. |
Python Solution | defuse-the-bomb | 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 have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
Python Solution | defuse-the-bomb | 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 integer array `nums` and an integer `goal`.
You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to **minimize the absolute difference** `abs(sum - goal)`.
Return _the ... | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. |
easy solution using array-manipulations | defuse-the-bomb | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nsince the array is circular append same array at end of array\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n> if key 0 store array of zeros in output\n\n> if key +ve prepare a temporary array of (array + array) &... | 0 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
easy solution using array-manipulations | defuse-the-bomb | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nsince the array is circular append same array at end of array\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n> if key 0 store array of zeros in output\n\n> if key +ve prepare a temporary array of (array + array) &... | 0 | You are given an integer array `nums` and an integer `goal`.
You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to **minimize the absolute difference** `abs(sum - goal)`.
Return _the ... | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. |
Python Solution for beginners and basic | defuse-the-bomb | 0 | 1 | # Intuition\nThe problem involves decrypting a given circular array based on a given key \'k\'. \nWe need to replace each element in the array according to specific rules based on the value of \'k\'.\n\n# Approach\n1. If k is non-negative, calculate the sum of the next \'k\' elements for each element in the array.\n2. ... | 0 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
Python Solution for beginners and basic | defuse-the-bomb | 0 | 1 | # Intuition\nThe problem involves decrypting a given circular array based on a given key \'k\'. \nWe need to replace each element in the array according to specific rules based on the value of \'k\'.\n\n# Approach\n1. If k is non-negative, calculate the sum of the next \'k\' elements for each element in the array.\n2. ... | 0 | You are given an integer array `nums` and an integer `goal`.
You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to **minimize the absolute difference** `abs(sum - goal)`.
Return _the ... | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. |
THE BEST SOLUTiON EVER by PRODONiK (Java, C++, C#, Python, Ruby) | defuse-the-bomb | 1 | 1 | \n\n# Intuition\nI aimed to decrypt an encoded message by summing up specific elements based on the provided key value.\n\n# Approach\nI checked whether the key value was negative, and if so, I reversed the... | 0 | You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **n... | Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left. |
THE BEST SOLUTiON EVER by PRODONiK (Java, C++, C#, Python, Ruby) | defuse-the-bomb | 1 | 1 | \n\n# Intuition\nI aimed to decrypt an encoded message by summing up specific elements based on the provided key value.\n\n# Approach\nI checked whether the key value was negative, and if so, I reversed the... | 0 | You are given an integer array `nums` and an integer `goal`.
You want to choose a subsequence of `nums` such that the sum of its elements is the closest possible to `goal`. That is, if the sum of the subsequence's elements is `sum`, then you want to **minimize the absolute difference** `abs(sum - goal)`.
Return _the ... | As the array is circular, use modulo to find the correct index. The constraints are low enough for a brute-force solution. |
Time O(n)/ Space O(1) Solution | minimum-deletions-to-make-string-balanced | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n[ Flip String to Monotone Increasing](https://leetcode.com/problems/flip-string-to-monotone-increasing/solutions/2912351/flip-string-to-monotone-increasing//)\n\nExactly Same\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time com... | 2 | You are given a string `s` consisting only of characters `'a'` and `'b'`.
You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`.
Return _the **minimum** number of deletions needed to ma... | Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2. |
Time O(n)/ Space O(1) Solution | minimum-deletions-to-make-string-balanced | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n[ Flip String to Monotone Increasing](https://leetcode.com/problems/flip-string-to-monotone-increasing/solutions/2912351/flip-string-to-monotone-increasing//)\n\nExactly Same\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time com... | 2 | Design a queue-like data structure that moves the most recently used element to the end of the queue.
Implement the `MRUQueue` class:
* `MRUQueue(int n)` constructs the `MRUQueue` with `n` elements: `[1,2,3,...,n]`.
* `int fetch(int k)` moves the `kth` element **(1-indexed)** to the end of the queue and returns i... | You need to find for every index the number of Bs before it and the number of A's after it You can speed up the finding of A's and B's in suffix and prefix using preprocessing |
✔ Python3 Solution | Clean & Concise | O(1) Space | minimum-deletions-to-make-string-balanced | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```Python\nclass Solution:\n def minimumDeletions(self, s):\n ans, count = 0, 0\n for i in s:\n if i == \'b\':\n count += 1\n elif count:\n ans += 1\n co... | 2 | You are given a string `s` consisting only of characters `'a'` and `'b'`.
You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`.
Return _the **minimum** number of deletions needed to ma... | Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2. |
✔ Python3 Solution | Clean & Concise | O(1) Space | minimum-deletions-to-make-string-balanced | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```Python\nclass Solution:\n def minimumDeletions(self, s):\n ans, count = 0, 0\n for i in s:\n if i == \'b\':\n count += 1\n elif count:\n ans += 1\n co... | 2 | Design a queue-like data structure that moves the most recently used element to the end of the queue.
Implement the `MRUQueue` class:
* `MRUQueue(int n)` constructs the `MRUQueue` with `n` elements: `[1,2,3,...,n]`.
* `int fetch(int k)` moves the `kth` element **(1-indexed)** to the end of the queue and returns i... | You need to find for every index the number of Bs before it and the number of A's after it You can speed up the finding of A's and B's in suffix and prefix using preprocessing |
Python easy to read and understand | stack | minimum-deletions-to-make-string-balanced | 0 | 1 | **Count the total number of ba pairs**\n```\nclass Solution:\n def minimumDeletions(self, s: str) -> int:\n stack, res = [], 0\n for i in range(len(s)):\n if stack and s[i] == "a" and stack[-1] == "b":\n stack.pop()\n res += 1\n else:\n ... | 9 | You are given a string `s` consisting only of characters `'a'` and `'b'`.
You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`.
Return _the **minimum** number of deletions needed to ma... | Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2. |
Python easy to read and understand | stack | minimum-deletions-to-make-string-balanced | 0 | 1 | **Count the total number of ba pairs**\n```\nclass Solution:\n def minimumDeletions(self, s: str) -> int:\n stack, res = [], 0\n for i in range(len(s)):\n if stack and s[i] == "a" and stack[-1] == "b":\n stack.pop()\n res += 1\n else:\n ... | 9 | Design a queue-like data structure that moves the most recently used element to the end of the queue.
Implement the `MRUQueue` class:
* `MRUQueue(int n)` constructs the `MRUQueue` with `n` elements: `[1,2,3,...,n]`.
* `int fetch(int k)` moves the `kth` element **(1-indexed)** to the end of the queue and returns i... | You need to find for every index the number of Bs before it and the number of A's after it You can speed up the finding of A's and B's in suffix and prefix using preprocessing |
[Python] DP solution easy to understand | minimum-deletions-to-make-string-balanced | 0 | 1 | * O(n) for loop each character of the string s\n* Track the minimum number of deletions to make a balanced string till current character, either ending with \'a\' or \'b\'.\n* In the end, find the min of these two numbers\n```\nclass Solution:\n def minimumDeletions(self, s: str) -> int:\n # track the minimum... | 14 | You are given a string `s` consisting only of characters `'a'` and `'b'`.
You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`.
Return _the **minimum** number of deletions needed to ma... | Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2. |
[Python] DP solution easy to understand | minimum-deletions-to-make-string-balanced | 0 | 1 | * O(n) for loop each character of the string s\n* Track the minimum number of deletions to make a balanced string till current character, either ending with \'a\' or \'b\'.\n* In the end, find the min of these two numbers\n```\nclass Solution:\n def minimumDeletions(self, s: str) -> int:\n # track the minimum... | 14 | Design a queue-like data structure that moves the most recently used element to the end of the queue.
Implement the `MRUQueue` class:
* `MRUQueue(int n)` constructs the `MRUQueue` with `n` elements: `[1,2,3,...,n]`.
* `int fetch(int k)` moves the `kth` element **(1-indexed)** to the end of the queue and returns i... | You need to find for every index the number of Bs before it and the number of A's after it You can speed up the finding of A's and B's in suffix and prefix using preprocessing |
Simple python solution using dynamic programming | minimum-deletions-to-make-string-balanced | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nclass Solution:\n def minimumDeletions(self, s: str) -> int:\n a_cnt = s.count(\'a\')\n res... | 2 | You are given a string `s` consisting only of characters `'a'` and `'b'`.
You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`.
Return _the **minimum** number of deletions needed to ma... | Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2. |
Simple python solution using dynamic programming | minimum-deletions-to-make-string-balanced | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nclass Solution:\n def minimumDeletions(self, s: str) -> int:\n a_cnt = s.count(\'a\')\n res... | 2 | Design a queue-like data structure that moves the most recently used element to the end of the queue.
Implement the `MRUQueue` class:
* `MRUQueue(int n)` constructs the `MRUQueue` with `n` elements: `[1,2,3,...,n]`.
* `int fetch(int k)` moves the `kth` element **(1-indexed)** to the end of the queue and returns i... | You need to find for every index the number of Bs before it and the number of A's after it You can speed up the finding of A's and B's in suffix and prefix using preprocessing |
70% TC and 78% SC easy python solution | minimum-deletions-to-make-string-balanced | 0 | 1 | ```\ndef minimumDeletions(self, s: str) -> int:\n\tstart = [0]\n\tlast = [0]\n\tfor i in s:\n\t\tstart.append(start[-1] + int(i=="b"))\n\tfor i in s[::-1]:\n\t\tlast.append(last[-1] + int(i=="a"))\n\tans = 10000000000\n\tfor i in range(len(start)):\n\t\tans = min(ans, start[i] + last[-i-1])\n\treturn ans\n``` | 1 | You are given a string `s` consisting only of characters `'a'` and `'b'`.
You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`.
Return _the **minimum** number of deletions needed to ma... | Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2. |
70% TC and 78% SC easy python solution | minimum-deletions-to-make-string-balanced | 0 | 1 | ```\ndef minimumDeletions(self, s: str) -> int:\n\tstart = [0]\n\tlast = [0]\n\tfor i in s:\n\t\tstart.append(start[-1] + int(i=="b"))\n\tfor i in s[::-1]:\n\t\tlast.append(last[-1] + int(i=="a"))\n\tans = 10000000000\n\tfor i in range(len(start)):\n\t\tans = min(ans, start[i] + last[-i-1])\n\treturn ans\n``` | 1 | Design a queue-like data structure that moves the most recently used element to the end of the queue.
Implement the `MRUQueue` class:
* `MRUQueue(int n)` constructs the `MRUQueue` with `n` elements: `[1,2,3,...,n]`.
* `int fetch(int k)` moves the `kth` element **(1-indexed)** to the end of the queue and returns i... | You need to find for every index the number of Bs before it and the number of A's after it You can speed up the finding of A's and B's in suffix and prefix using preprocessing |
Python Stack | Beats 95% | minimum-deletions-to-make-string-balanced | 0 | 1 | ```\nclass Solution:\n def minimumDeletions(self, s: str) -> int:\n count = 0\n stack = [] \n for c in s:\n if c == \'b\':\n stack.append(c)\n elif stack:\n stack.pop()\n count += 1\n return count\n \n... | 4 | You are given a string `s` consisting only of characters `'a'` and `'b'`.
You can delete any number of characters in `s` to make `s` **balanced**. `s` is **balanced** if there is no pair of indices `(i,j)` such that `i < j` and `s[i] = 'b'` and `s[j]= 'a'`.
Return _the **minimum** number of deletions needed to ma... | Start DFS from each leaf node. stop the DFS when the number of steps done > distance. If you reach another leaf node within distance steps, add 1 to the answer. Note that all pairs will be counted twice so divide the answer by 2. |
Python Stack | Beats 95% | minimum-deletions-to-make-string-balanced | 0 | 1 | ```\nclass Solution:\n def minimumDeletions(self, s: str) -> int:\n count = 0\n stack = [] \n for c in s:\n if c == \'b\':\n stack.append(c)\n elif stack:\n stack.pop()\n count += 1\n return count\n \n... | 4 | Design a queue-like data structure that moves the most recently used element to the end of the queue.
Implement the `MRUQueue` class:
* `MRUQueue(int n)` constructs the `MRUQueue` with `n` elements: `[1,2,3,...,n]`.
* `int fetch(int k)` moves the `kth` element **(1-indexed)** to the end of the queue and returns i... | You need to find for every index the number of Bs before it and the number of A's after it You can speed up the finding of A's and B's in suffix and prefix using preprocessing |
Python, DFS (issue with 121 test case solved) | minimum-jumps-to-reach-home | 0 | 1 | **UPD:**\n\nI believe I have found the issue: I should be able to go back more if my back step is larger than my forward step. Thanks to @ShidaLei\n for pointing it out.\n\n----------------------------------------------------------------------------------------------------------------\nUpdated, working DFS solution, st... | 22 | A certain bug's home is on the x-axis at position `x`. Help them get there from position `0`.
The bug jumps according to the following rules:
* It can jump exactly `a` positions **forward** (to the right).
* It can jump exactly `b` positions **backward** (to the left).
* It cannot jump backward twice in a row.
... | null |
Fast Python and C++ solution with explanation - BFS | minimum-jumps-to-reach-home | 0 | 1 | The objective is to find the minimum number of hops. BFS is the ideal candidate for this question since it will provide the shortest path.\n**Solution:**\n1. We start exploring from `0` position. \n2. At each position, we can either go forward by `a` and go backward by `b`. Thing to note here is we cannot go backward t... | 23 | A certain bug's home is on the x-axis at position `x`. Help them get there from position `0`.
The bug jumps according to the following rules:
* It can jump exactly `a` positions **forward** (to the right).
* It can jump exactly `b` positions **backward** (to the left).
* It cannot jump backward twice in a row.
... | null |
Python3 - BFS - beats 100% - with Explanation 🔥🔥🔥 | minimum-jumps-to-reach-home | 0 | 1 | # Intuition\r\n- We use BFS to find the minimum number of jumps required to reach the target position from the starting position.\r\n\r\n- We consider two types of moves: a forward jump of size \'a\', and a backward jump of size \'b\'.\r\n\r\n- We avoid forbidden positions, jumping backwards twice in a row and jumping ... | 3 | A certain bug's home is on the x-axis at position `x`. Help them get there from position `0`.
The bug jumps according to the following rules:
* It can jump exactly `a` positions **forward** (to the right).
* It can jump exactly `b` positions **backward** (to the left).
* It cannot jump backward twice in a row.
... | null |
[Python3] BFS - easy understanding | minimum-jumps-to-reach-home | 0 | 1 | ```\ndef minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int:\n visited = set()\n q = deque([(0, 0)])\n forbidden = set(forbidden)\n furthest = max(x, max(forbidden)) + a + b\n \n res = 0\n while q:\n n = len(q)\n for _ in range(... | 5 | A certain bug's home is on the x-axis at position `x`. Help them get there from position `0`.
The bug jumps according to the following rules:
* It can jump exactly `a` positions **forward** (to the right).
* It can jump exactly `b` positions **backward** (to the left).
* It cannot jump backward twice in a row.
... | null |
[Python3] Dead simple backtracking - faster than 98% | distribute-repeating-integers | 0 | 1 | 1. Sort the `quantity` array in reverse order, since allocating larger quantities first will more quickly reduce the search space.\n2. Get the frequency of each number in `nums`, ignoring the actual numbers.\n3. Then further get the count of each frequency, storing this in `freqCounts`. We do this so that in our backtr... | 6 | You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible to distribute `nums` such that:
* Th... | Disconnect node p from its parent and append it to the children list of node q. If q was in the sub-tree of node p (case 1), get the parent node of p and replace p in its children list with q. If p was the root of the tree, make q the root of the tree. |
[Python3] Dead simple backtracking - faster than 98% | distribute-repeating-integers | 0 | 1 | 1. Sort the `quantity` array in reverse order, since allocating larger quantities first will more quickly reduce the search space.\n2. Get the frequency of each number in `nums`, ignoring the actual numbers.\n3. Then further get the count of each frequency, storing this in `freqCounts`. We do this so that in our backtr... | 6 | You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not.
Return _the **m... | Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to ... |
Simple and clear python3 solutions | Backtracking + Recursion | distribute-repeating-integers | 0 | 1 | # Complexity\n- Time complexity: $$O(n + m \\cdot log(m) + k^m)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(k + m)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nwhere `n = nums.length`, `m = quantity.length`, `k = nums.unique`\n\n# Code\n``` python3 []\nclass Solut... | 0 | You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible to distribute `nums` such that:
* Th... | Disconnect node p from its parent and append it to the children list of node q. If q was in the sub-tree of node p (case 1), get the parent node of p and replace p in its children list with q. If p was the root of the tree, make q the root of the tree. |
Simple and clear python3 solutions | Backtracking + Recursion | distribute-repeating-integers | 0 | 1 | # Complexity\n- Time complexity: $$O(n + m \\cdot log(m) + k^m)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(k + m)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nwhere `n = nums.length`, `m = quantity.length`, `k = nums.unique`\n\n# Code\n``` python3 []\nclass Solut... | 0 | You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not.
Return _the **m... | Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to ... |
Python - 8 lines | distribute-repeating-integers | 0 | 1 | # Complexity\n- Time complexity:\n$$O(C 2^n)$$\n\n\n# Code\n```\nclass Solution:\n def canDistribute(self, nums, quantity) -> bool:\n quantity, A = sorted(quantity, reverse=True), list(Counter(nums).values())\n def check(customer):\n for i in range(len(A)):\n if A[i] >= quanti... | 0 | You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible to distribute `nums` such that:
* Th... | Disconnect node p from its parent and append it to the children list of node q. If q was in the sub-tree of node p (case 1), get the parent node of p and replace p in its children list with q. If p was the root of the tree, make q the root of the tree. |
Python - 8 lines | distribute-repeating-integers | 0 | 1 | # Complexity\n- Time complexity:\n$$O(C 2^n)$$\n\n\n# Code\n```\nclass Solution:\n def canDistribute(self, nums, quantity) -> bool:\n quantity, A = sorted(quantity, reverse=True), list(Counter(nums).values())\n def check(customer):\n for i in range(len(A)):\n if A[i] >= quanti... | 0 | You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not.
Return _the **m... | Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to ... |
Backtracking with Memoization | Commented and Explained | distribute-repeating-integers | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe know we only have 10 customers at worst. We also know we have at most 50 unique items in our set up. We can backtrack on the customers and on the items, and can limit ourselves to only as many items as we have customers if we go in gre... | 0 | You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible to distribute `nums` such that:
* Th... | Disconnect node p from its parent and append it to the children list of node q. If q was in the sub-tree of node p (case 1), get the parent node of p and replace p in its children list with q. If p was the root of the tree, make q the root of the tree. |
Backtracking with Memoization | Commented and Explained | distribute-repeating-integers | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe know we only have 10 customers at worst. We also know we have at most 50 unique items in our set up. We can backtrack on the customers and on the items, and can limit ourselves to only as many items as we have customers if we go in gre... | 0 | You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not.
Return _the **m... | Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to ... |
Python (Simple Backtracking) | distribute-repeating-integers | 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 of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible to distribute `nums` such that:
* Th... | Disconnect node p from its parent and append it to the children list of node q. If q was in the sub-tree of node p (case 1), get the parent node of p and replace p in its children list with q. If p was the root of the tree, make q the root of the tree. |
Python (Simple Backtracking) | distribute-repeating-integers | 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 `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not.
Return _the **m... | Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to ... |
[Python3] simple solution | design-an-ordered-stream | 0 | 1 | \n```\nclass OrderedStream:\n\n def __init__(self, n: int):\n self.data = [None]*n\n self.ptr = 0 # 0-indexed \n\n def insert(self, id: int, value: str) -> List[str]:\n id -= 1 # 0-indexed \n self.data[id] = value \n if id > self.ptr: return [] # not reaching ptr \n \n ... | 55 | There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`.
Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each... | Notice that the constraints are small enough for a brute force solution to pass. Loop through all triplets, and count the ones that are good. |
[Python3] simple solution | design-an-ordered-stream | 0 | 1 | \n```\nclass OrderedStream:\n\n def __init__(self, n: int):\n self.data = [None]*n\n self.ptr = 0 # 0-indexed \n\n def insert(self, id: int, value: str) -> List[str]:\n id -= 1 # 0-indexed \n self.data[id] = value \n if id > self.ptr: return [] # not reaching ptr \n \n ... | 55 | 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 with a hint before the solution. | design-an-ordered-stream | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nIf you don\'t want to go through my code, I suggest you to watch the example video and observe the "ptr" and how it is incrementing and returning things based on the ptr value.\n\n# Code\n```\nclass OrderedStream:\n\n def __init__(self, n: int):\n ... | 2 | There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`.
Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each... | Notice that the constraints are small enough for a brute force solution to pass. Loop through all triplets, and count the ones that are good. |
Python solution with a hint before the solution. | design-an-ordered-stream | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nIf you don\'t want to go through my code, I suggest you to watch the example video and observe the "ptr" and how it is incrementing and returning things based on the ptr value.\n\n# Code\n```\nclass OrderedStream:\n\n def __init__(self, n: int):\n ... | 2 | 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. |
Latest Python solution explained for newly updated description: Faster than 90% | design-an-ordered-stream | 0 | 1 | The idea behind this problem is simple but the description is confusing.\nSo let me explain a bit.\n\nBasically , we need to store every incoming value at the given index. And \nwith every incoming index, we have to check\n\n* If the current index is less than the incoming index, the we have to return\n an empty lis... | 29 | There is a stream of `n` `(idKey, value)` pairs arriving in an **arbitrary** order, where `idKey` is an integer between `1` and `n` and `value` is a string. No two pairs have the same `id`.
Design a stream that returns the values in **increasing order of their IDs** by returning a **chunk** (list) of values after each... | Notice that the constraints are small enough for a brute force solution to pass. Loop through all triplets, and count the ones that are good. |
Latest Python solution explained for newly updated description: Faster than 90% | design-an-ordered-stream | 0 | 1 | The idea behind this problem is simple but the description is confusing.\nSo let me explain a bit.\n\nBasically , we need to store every incoming value at the given index. And \nwith every incoming index, we have to check\n\n* If the current index is less than the incoming index, the we have to return\n an empty lis... | 29 | 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. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.